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