Follow-up 8697ba8: No need for two dependencies on the same module
[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 global $wgActorTableSchemaMigrationStage;
1250
1251 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1252 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1253 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1254 'site_stats', 'ipblocks', 'image', 'oldimage',
1255 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1256 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1257 'archive', 'user_groups', 'page_props', 'category',
1258 'slots', 'content', 'slot_roles', 'content_models',
1259 'comment', 'revision_comment_temp',
1260 ];
1261
1262 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1263 // The new tables for actors are in use
1264 $tables[] = 'actor';
1265 $tables[] = 'revision_actor_temp';
1266 }
1267
1268 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite' ] ) ) {
1269 array_push( $tables, 'searchindex' );
1270 }
1271
1272 // Allow extensions to add to the list of tables to duplicate;
1273 // may be necessary if they hook into page save or other code
1274 // which will require them while running tests.
1275 Hooks::run( 'ParserTestTables', [ &$tables ] );
1276
1277 return $tables;
1278 }
1279
1280 public function setDatabase( IDatabase $db ) {
1281 $this->db = $db;
1282 $this->setupDone['setDatabase'] = true;
1283 }
1284
1285 /**
1286 * Set up temporary DB tables.
1287 *
1288 * For best performance, call this once only for all tests. However, it can
1289 * be called at the start of each test if more isolation is desired.
1290 *
1291 * @todo This is basically an unrefactored copy of
1292 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1293 *
1294 * Do not call this function from a MediaWikiTestCase subclass, since
1295 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1296 *
1297 * @see staticSetup() for more information about setup/teardown
1298 *
1299 * @param ScopedCallback|null $nextTeardown The next teardown object
1300 * @return ScopedCallback The teardown object
1301 */
1302 public function setupDatabase( $nextTeardown = null ) {
1303 global $wgDBprefix;
1304
1305 $this->db = MediaWikiServices::getInstance()->getDBLoadBalancer()->getConnection( DB_MASTER );
1306 $dbType = $this->db->getType();
1307
1308 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1309 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1310 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1311 }
1312
1313 $teardown = [];
1314
1315 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1316
1317 # CREATE TEMPORARY TABLE breaks if there is more than one server
1318 if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1319 $this->useTemporaryTables = false;
1320 }
1321
1322 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1323 $prefix = 'parsertest_';
1324
1325 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1326 $this->dbClone->useTemporaryTables( $temporary );
1327 $this->dbClone->cloneTableStructure();
1328 CloneDatabase::changePrefix( $prefix );
1329
1330 $teardown[] = function () {
1331 $this->teardownDatabase();
1332 };
1333
1334 // Wipe some DB query result caches on setup and teardown
1335 $reset = function () {
1336 MediaWikiServices::getInstance()->getLinkCache()->clear();
1337
1338 // Clear the message cache
1339 MessageCache::singleton()->clear();
1340 };
1341 $reset();
1342 $teardown[] = $reset;
1343 return $this->createTeardownObject( $teardown, $nextTeardown );
1344 }
1345
1346 /**
1347 * Add data about uploads to the new test DB, and set up the upload
1348 * directory. This should be called after either setDatabase() or
1349 * setupDatabase().
1350 *
1351 * @param ScopedCallback|null $nextTeardown The next teardown object
1352 * @return ScopedCallback The teardown object
1353 */
1354 public function setupUploads( $nextTeardown = null ) {
1355 $teardown = [];
1356
1357 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1358 $teardown[] = $this->markSetupDone( 'setupUploads' );
1359
1360 // Create the files in the upload directory (or pretend to create them
1361 // in a MockFileBackend). Append teardown callback.
1362 $teardown[] = $this->setupUploadBackend();
1363
1364 // Create a user
1365 $user = User::createNew( 'WikiSysop' );
1366
1367 // Register the uploads in the database
1368
1369 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1370 # note that the size/width/height/bits/etc of the file
1371 # are actually set by inspecting the file itself; the arguments
1372 # to recordUpload2 have no effect. That said, we try to make things
1373 # match up so it is less confusing to readers of the code & tests.
1374 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1375 'size' => 7881,
1376 'width' => 1941,
1377 'height' => 220,
1378 'bits' => 8,
1379 'media_type' => MEDIATYPE_BITMAP,
1380 'mime' => 'image/jpeg',
1381 'metadata' => serialize( [] ),
1382 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1383 'fileExists' => true
1384 ], $this->db->timestamp( '20010115123500' ), $user );
1385
1386 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1387 # again, note that size/width/height below are ignored; see above.
1388 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1389 'size' => 22589,
1390 'width' => 135,
1391 'height' => 135,
1392 'bits' => 8,
1393 'media_type' => MEDIATYPE_BITMAP,
1394 'mime' => 'image/png',
1395 'metadata' => serialize( [] ),
1396 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1397 'fileExists' => true
1398 ], $this->db->timestamp( '20130225203040' ), $user );
1399
1400 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1401 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1402 'size' => 12345,
1403 'width' => 240,
1404 'height' => 180,
1405 'bits' => 0,
1406 'media_type' => MEDIATYPE_DRAWING,
1407 'mime' => 'image/svg+xml',
1408 'metadata' => serialize( [
1409 'version' => SvgHandler::SVG_METADATA_VERSION,
1410 'width' => 240,
1411 'height' => 180,
1412 'originalWidth' => '100%',
1413 'originalHeight' => '100%',
1414 'translations' => [
1415 'en' => SVGReader::LANG_FULL_MATCH,
1416 'ru' => SVGReader::LANG_FULL_MATCH,
1417 ],
1418 ] ),
1419 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1420 'fileExists' => true
1421 ], $this->db->timestamp( '20010115123500' ), $user );
1422
1423 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1424 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1425 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1426 'size' => 12345,
1427 'width' => 320,
1428 'height' => 240,
1429 'bits' => 24,
1430 'media_type' => MEDIATYPE_BITMAP,
1431 'mime' => 'image/jpeg',
1432 'metadata' => serialize( [] ),
1433 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1434 'fileExists' => true
1435 ], $this->db->timestamp( '20010115123500' ), $user );
1436
1437 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1438 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1439 'size' => 12345,
1440 'width' => 320,
1441 'height' => 240,
1442 'bits' => 0,
1443 'media_type' => MEDIATYPE_VIDEO,
1444 'mime' => 'application/ogg',
1445 'metadata' => serialize( [] ),
1446 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1447 'fileExists' => true
1448 ], $this->db->timestamp( '20010115123500' ), $user );
1449
1450 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1451 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1452 'size' => 12345,
1453 'width' => 0,
1454 'height' => 0,
1455 'bits' => 0,
1456 'media_type' => MEDIATYPE_AUDIO,
1457 'mime' => 'application/ogg',
1458 'metadata' => serialize( [] ),
1459 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1460 'fileExists' => true
1461 ], $this->db->timestamp( '20010115123500' ), $user );
1462
1463 # A DjVu file
1464 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1465 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1466 'size' => 3249,
1467 'width' => 2480,
1468 'height' => 3508,
1469 'bits' => 0,
1470 'media_type' => MEDIATYPE_BITMAP,
1471 'mime' => 'image/vnd.djvu',
1472 'metadata' => '<?xml version="1.0" ?>
1473 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1474 <DjVuXML>
1475 <HEAD></HEAD>
1476 <BODY><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 <OBJECT height="3508" width="2480">
1489 <PARAM name="DPI" value="300" />
1490 <PARAM name="GAMMA" value="2.2" />
1491 </OBJECT>
1492 <OBJECT height="3508" width="2480">
1493 <PARAM name="DPI" value="300" />
1494 <PARAM name="GAMMA" value="2.2" />
1495 </OBJECT>
1496 </BODY>
1497 </DjVuXML>',
1498 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1499 'fileExists' => true
1500 ], $this->db->timestamp( '20010115123600' ), $user );
1501
1502 return $this->createTeardownObject( $teardown, $nextTeardown );
1503 }
1504
1505 /**
1506 * Helper for database teardown, called from the teardown closure. Destroy
1507 * the database clone and fix up some things that CloneDatabase doesn't fix.
1508 *
1509 * @todo Move most things here to CloneDatabase
1510 */
1511 private function teardownDatabase() {
1512 $this->checkSetupDone( 'setupDatabase' );
1513
1514 $this->dbClone->destroy();
1515
1516 if ( $this->useTemporaryTables ) {
1517 if ( $this->db->getType() == 'sqlite' ) {
1518 # Under SQLite the searchindex table is virtual and need
1519 # to be explicitly destroyed. See T31912
1520 # See also MediaWikiTestCase::destroyDB()
1521 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1522 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1523 }
1524 # Don't need to do anything
1525 return;
1526 }
1527
1528 $tables = $this->listTables();
1529
1530 foreach ( $tables as $table ) {
1531 $this->db->query( "DROP TABLE `parsertest_$table`" );
1532 }
1533 }
1534
1535 /**
1536 * Upload test files to the backend created by createRepoGroup().
1537 *
1538 * @return callable The teardown callback
1539 */
1540 private function setupUploadBackend() {
1541 global $IP;
1542
1543 $repo = RepoGroup::singleton()->getLocalRepo();
1544 $base = $repo->getZonePath( 'public' );
1545 $backend = $repo->getBackend();
1546 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1547 $backend->store( [
1548 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1549 'dst' => "$base/3/3a/Foobar.jpg"
1550 ] );
1551 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1552 $backend->store( [
1553 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1554 'dst' => "$base/e/ea/Thumb.png"
1555 ] );
1556 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1557 $backend->store( [
1558 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1559 'dst' => "$base/0/09/Bad.jpg"
1560 ] );
1561 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1562 $backend->store( [
1563 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1564 'dst' => "$base/5/5f/LoremIpsum.djvu"
1565 ] );
1566
1567 // No helpful SVG file to copy, so make one ourselves
1568 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1569 '<svg xmlns="http://www.w3.org/2000/svg"' .
1570 ' version="1.1" width="240" height="180"/>';
1571
1572 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1573 $backend->quickCreate( [
1574 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1575 ] );
1576
1577 return function () use ( $backend ) {
1578 if ( $backend instanceof MockFileBackend ) {
1579 // In memory backend, so dont bother cleaning them up.
1580 return;
1581 }
1582 $this->teardownUploadBackend();
1583 };
1584 }
1585
1586 /**
1587 * Remove the dummy uploads directory
1588 */
1589 private function teardownUploadBackend() {
1590 if ( $this->keepUploads ) {
1591 return;
1592 }
1593
1594 $repo = RepoGroup::singleton()->getLocalRepo();
1595 $public = $repo->getZonePath( 'public' );
1596
1597 $this->deleteFiles(
1598 [
1599 "$public/3/3a/Foobar.jpg",
1600 "$public/e/ea/Thumb.png",
1601 "$public/0/09/Bad.jpg",
1602 "$public/5/5f/LoremIpsum.djvu",
1603 "$public/f/ff/Foobar.svg",
1604 "$public/0/00/Video.ogv",
1605 "$public/4/41/Audio.oga",
1606 ]
1607 );
1608 }
1609
1610 /**
1611 * Delete the specified files and their parent directories
1612 * @param array $files File backend URIs mwstore://...
1613 */
1614 private function deleteFiles( $files ) {
1615 // Delete the files
1616 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1617 foreach ( $files as $file ) {
1618 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1619 }
1620
1621 // Delete the parent directories
1622 foreach ( $files as $file ) {
1623 $tmp = FileBackend::parentStoragePath( $file );
1624 while ( $tmp ) {
1625 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1626 break;
1627 }
1628 $tmp = FileBackend::parentStoragePath( $tmp );
1629 }
1630 }
1631 }
1632
1633 /**
1634 * Add articles to the test DB.
1635 *
1636 * @param array $articles Article info array from TestFileReader
1637 */
1638 public function addArticles( $articles ) {
1639 $setup = [];
1640 $teardown = [];
1641
1642 // Be sure ParserTestRunner::addArticle has correct language set,
1643 // so that system messages get into the right language cache
1644 if ( MediaWikiServices::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1645 $setup['wgLanguageCode'] = 'en';
1646 $lang = Language::factory( 'en' );
1647 $setup['wgContLang'] = $lang;
1648 $setup[] = function () use ( $lang ) {
1649 $services = MediaWikiServices::getInstance();
1650 $services->disableService( 'ContentLanguage' );
1651 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1652 return $lang;
1653 } );
1654 };
1655 $teardown[] = function () {
1656 MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1657 };
1658 }
1659
1660 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1661 $this->appendNamespaceSetup( $setup, $teardown );
1662
1663 // wgCapitalLinks obviously needs initialisation
1664 $setup['wgCapitalLinks'] = true;
1665
1666 $teardown[] = $this->executeSetupSnippets( $setup );
1667
1668 foreach ( $articles as $info ) {
1669 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1670 }
1671
1672 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1673 // due to T144706
1674 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
1675
1676 $this->executeSetupSnippets( $teardown );
1677 }
1678
1679 /**
1680 * Insert a temporary test article
1681 * @param string $name The title, including any prefix
1682 * @param string $text The article text
1683 * @param string $file The input file name
1684 * @param int|string $line The input line number, for reporting errors
1685 * @throws Exception
1686 * @throws MWException
1687 */
1688 private function addArticle( $name, $text, $file, $line ) {
1689 $text = self::chomp( $text );
1690 $name = self::chomp( $name );
1691
1692 $title = Title::newFromText( $name );
1693 wfDebug( __METHOD__ . ": adding $name" );
1694
1695 if ( is_null( $title ) ) {
1696 throw new MWException( "invalid title '$name' at $file:$line\n" );
1697 }
1698
1699 $newContent = ContentHandler::makeContent( $text, $title );
1700
1701 $page = WikiPage::factory( $title );
1702 $page->loadPageData( 'fromdbmaster' );
1703
1704 if ( $page->exists() ) {
1705 $content = $page->getContent( Revision::RAW );
1706 // Only reject the title, if the content/content model is different.
1707 // This makes it easier to create Template:(( or Template:)) in different extensions
1708 if ( $newContent->equals( $content ) ) {
1709 return;
1710 }
1711 throw new MWException(
1712 "duplicate article '$name' with different content at $file:$line\n"
1713 );
1714 }
1715
1716 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1717 // But initialise the MessageCache clone first, don't let MessageCache
1718 // get a reference to the mock object.
1719 if ( $this->disableSaveParse ) {
1720 MessageCache::singleton()->getParser();
1721 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser ] );
1722 } else {
1723 $restore = false;
1724 }
1725 try {
1726 $status = $page->doEditContent(
1727 $newContent,
1728 '',
1729 EDIT_NEW | EDIT_INTERNAL
1730 );
1731 } finally {
1732 if ( $restore ) {
1733 $restore();
1734 }
1735 }
1736
1737 if ( !$status->isOK() ) {
1738 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1739 }
1740
1741 // The RepoGroup cache is invalidated by the creation of file redirects
1742 if ( $title->inNamespace( NS_FILE ) ) {
1743 RepoGroup::singleton()->clearCache( $title );
1744 }
1745 }
1746
1747 /**
1748 * Check if a hook is installed
1749 *
1750 * @param string $name
1751 * @return bool True if tag hook is present
1752 */
1753 public function requireHook( $name ) {
1754 $parser = MediaWikiServices::getInstance()->getParser();
1755
1756 $parser->firstCallInit(); // make sure hooks are loaded.
1757 if ( isset( $parser->mTagHooks[$name] ) ) {
1758 return true;
1759 } else {
1760 $this->recorder->warning( " This test suite requires the '$name' hook " .
1761 "extension, skipping." );
1762 return false;
1763 }
1764 }
1765
1766 /**
1767 * Check if a function hook is installed
1768 *
1769 * @param string $name
1770 * @return bool True if function hook is present
1771 */
1772 public function requireFunctionHook( $name ) {
1773 $parser = MediaWikiServices::getInstance()->getParser();
1774
1775 $parser->firstCallInit(); // make sure hooks are loaded.
1776
1777 if ( isset( $parser->mFunctionHooks[$name] ) ) {
1778 return true;
1779 } else {
1780 $this->recorder->warning( " This test suite requires the '$name' function " .
1781 "hook extension, skipping." );
1782 return false;
1783 }
1784 }
1785
1786 /**
1787 * Check if a transparent tag hook is installed
1788 *
1789 * @param string $name
1790 * @return bool True if function hook is present
1791 */
1792 public function requireTransparentHook( $name ) {
1793 $parser = MediaWikiServices::getInstance()->getParser();
1794
1795 $parser->firstCallInit(); // make sure hooks are loaded.
1796
1797 if ( isset( $parser->mTransparentTagHooks[$name] ) ) {
1798 return true;
1799 } else {
1800 $this->recorder->warning( " This test suite requires the '$name' transparent " .
1801 "hook extension, skipping.\n" );
1802 return false;
1803 }
1804 }
1805
1806 /**
1807 * Fake constant timestamp to make sure time-related parser
1808 * functions give a persistent value.
1809 *
1810 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1811 * - Parser::preSaveTransform (via ParserOptions)
1812 */
1813 private function getFakeTimestamp() {
1814 // parsed as '1970-01-01T00:02:03Z'
1815 return 123;
1816 }
1817 }