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