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