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