build: Update mediawiki/mediawiki-codesniffer to 0.10.1
[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 $setup = [
1040 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
1041 'wgLanguageCode' => $langCode,
1042 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
1043 'wgNamespacesWithSubpages' => array_fill_keys(
1044 MWNamespace::getValidNamespaces(), isset( $opts['subpage'] )
1045 ),
1046 'wgMaxTocLevel' => $maxtoclevel,
1047 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1048 'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
1049 'wgDefaultLanguageVariant' => $variant,
1050 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1051 // Set as a JSON object like:
1052 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1053 'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1054 + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1055 ];
1056
1057 if ( $config ) {
1058 $configLines = explode( "\n", $config );
1059
1060 foreach ( $configLines as $line ) {
1061 list( $var, $value ) = explode( '=', $line, 2 );
1062 $setup[$var] = eval( "return $value;" );
1063 }
1064 }
1065
1066 /** @since 1.20 */
1067 Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1068
1069 // Create tidy driver
1070 if ( isset( $opts['tidy'] ) ) {
1071 // Cache a driver instance
1072 if ( $this->tidyDriver === null ) {
1073 $this->tidyDriver = MWTidy::factory( $this->tidySupport->getConfig() );
1074 }
1075 $tidy = $this->tidyDriver;
1076 } else {
1077 $tidy = false;
1078 }
1079 MWTidy::setInstance( $tidy );
1080 $teardown[] = function () {
1081 MWTidy::destroySingleton();
1082 };
1083
1084 // Set content language. This invalidates the magic word cache and title services
1085 $lang = Language::factory( $langCode );
1086 $setup['wgContLang'] = $lang;
1087 $reset = function () {
1088 MagicWord::clearCache();
1089 $this->resetTitleServices();
1090 };
1091 $setup[] = $reset;
1092 $teardown[] = $reset;
1093
1094 // Make a user object with the same language
1095 $user = new User;
1096 $user->setOption( 'language', $langCode );
1097 $setup['wgLang'] = $lang;
1098
1099 // We (re)set $wgThumbLimits to a single-element array above.
1100 $user->setOption( 'thumbsize', 0 );
1101
1102 $setup['wgUser'] = $user;
1103
1104 // And put both user and language into the context
1105 $context = RequestContext::getMain();
1106 $context->setUser( $user );
1107 $context->setLanguage( $lang );
1108 $teardown[] = function () use ( $context ) {
1109 // Clear language conversion tables
1110 $wrapper = TestingAccessWrapper::newFromObject(
1111 $context->getLanguage()->getConverter()
1112 );
1113 $wrapper->reloadTables();
1114 // Reset context to the restored globals
1115 $context->setUser( $GLOBALS['wgUser'] );
1116 $context->setLanguage( $GLOBALS['wgContLang'] );
1117 };
1118
1119 $teardown[] = $this->executeSetupSnippets( $setup );
1120
1121 return $this->createTeardownObject( $teardown, $nextTeardown );
1122 }
1123
1124 /**
1125 * List of temporary tables to create, without prefix.
1126 * Some of these probably aren't necessary.
1127 * @return array
1128 */
1129 private function listTables() {
1130 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1131 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1132 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1133 'site_stats', 'ipblocks', 'image', 'oldimage',
1134 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1135 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1136 'archive', 'user_groups', 'page_props', 'category'
1137 ];
1138
1139 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1140 array_push( $tables, 'searchindex' );
1141 }
1142
1143 // Allow extensions to add to the list of tables to duplicate;
1144 // may be necessary if they hook into page save or other code
1145 // which will require them while running tests.
1146 Hooks::run( 'ParserTestTables', [ &$tables ] );
1147
1148 return $tables;
1149 }
1150
1151 public function setDatabase( IDatabase $db ) {
1152 $this->db = $db;
1153 $this->setupDone['setDatabase'] = true;
1154 }
1155
1156 /**
1157 * Set up temporary DB tables.
1158 *
1159 * For best performance, call this once only for all tests. However, it can
1160 * be called at the start of each test if more isolation is desired.
1161 *
1162 * @todo: This is basically an unrefactored copy of
1163 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1164 *
1165 * Do not call this function from a MediaWikiTestCase subclass, since
1166 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1167 *
1168 * @see staticSetup() for more information about setup/teardown
1169 *
1170 * @param ScopedCallback|null $nextTeardown The next teardown object
1171 * @return ScopedCallback The teardown object
1172 */
1173 public function setupDatabase( $nextTeardown = null ) {
1174 global $wgDBprefix;
1175
1176 $this->db = wfGetDB( DB_MASTER );
1177 $dbType = $this->db->getType();
1178
1179 if ( $dbType == 'oracle' ) {
1180 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1181 } else {
1182 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1183 }
1184 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1185 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1186 }
1187
1188 $teardown = [];
1189
1190 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1191
1192 # CREATE TEMPORARY TABLE breaks if there is more than one server
1193 if ( wfGetLB()->getServerCount() != 1 ) {
1194 $this->useTemporaryTables = false;
1195 }
1196
1197 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1198 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1199
1200 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1201 $this->dbClone->useTemporaryTables( $temporary );
1202 $this->dbClone->cloneTableStructure();
1203
1204 if ( $dbType == 'oracle' ) {
1205 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1206 # Insert 0 user to prevent FK violations
1207
1208 # Anonymous user
1209 $this->db->insert( 'user', [
1210 'user_id' => 0,
1211 'user_name' => 'Anonymous' ] );
1212 }
1213
1214 $teardown[] = function () {
1215 $this->teardownDatabase();
1216 };
1217
1218 // Wipe some DB query result caches on setup and teardown
1219 $reset = function () {
1220 LinkCache::singleton()->clear();
1221
1222 // Clear the message cache
1223 MessageCache::singleton()->clear();
1224 };
1225 $reset();
1226 $teardown[] = $reset;
1227 return $this->createTeardownObject( $teardown, $nextTeardown );
1228 }
1229
1230 /**
1231 * Add data about uploads to the new test DB, and set up the upload
1232 * directory. This should be called after either setDatabase() or
1233 * setupDatabase().
1234 *
1235 * @param ScopedCallback|null $nextTeardown The next teardown object
1236 * @return ScopedCallback The teardown object
1237 */
1238 public function setupUploads( $nextTeardown = null ) {
1239 $teardown = [];
1240
1241 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1242 $teardown[] = $this->markSetupDone( 'setupUploads' );
1243
1244 // Create the files in the upload directory (or pretend to create them
1245 // in a MockFileBackend). Append teardown callback.
1246 $teardown[] = $this->setupUploadBackend();
1247
1248 // Create a user
1249 $user = User::createNew( 'WikiSysop' );
1250
1251 // Register the uploads in the database
1252
1253 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1254 # note that the size/width/height/bits/etc of the file
1255 # are actually set by inspecting the file itself; the arguments
1256 # to recordUpload2 have no effect. That said, we try to make things
1257 # match up so it is less confusing to readers of the code & tests.
1258 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1259 'size' => 7881,
1260 'width' => 1941,
1261 'height' => 220,
1262 'bits' => 8,
1263 'media_type' => MEDIATYPE_BITMAP,
1264 'mime' => 'image/jpeg',
1265 'metadata' => serialize( [] ),
1266 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1267 'fileExists' => true
1268 ], $this->db->timestamp( '20010115123500' ), $user );
1269
1270 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1271 # again, note that size/width/height below are ignored; see above.
1272 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1273 'size' => 22589,
1274 'width' => 135,
1275 'height' => 135,
1276 'bits' => 8,
1277 'media_type' => MEDIATYPE_BITMAP,
1278 'mime' => 'image/png',
1279 'metadata' => serialize( [] ),
1280 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1281 'fileExists' => true
1282 ], $this->db->timestamp( '20130225203040' ), $user );
1283
1284 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1285 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1286 'size' => 12345,
1287 'width' => 240,
1288 'height' => 180,
1289 'bits' => 0,
1290 'media_type' => MEDIATYPE_DRAWING,
1291 'mime' => 'image/svg+xml',
1292 'metadata' => serialize( [] ),
1293 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1294 'fileExists' => true
1295 ], $this->db->timestamp( '20010115123500' ), $user );
1296
1297 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1298 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1299 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1300 'size' => 12345,
1301 'width' => 320,
1302 'height' => 240,
1303 'bits' => 24,
1304 'media_type' => MEDIATYPE_BITMAP,
1305 'mime' => 'image/jpeg',
1306 'metadata' => serialize( [] ),
1307 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1308 'fileExists' => true
1309 ], $this->db->timestamp( '20010115123500' ), $user );
1310
1311 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1312 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1313 'size' => 12345,
1314 'width' => 320,
1315 'height' => 240,
1316 'bits' => 0,
1317 'media_type' => MEDIATYPE_VIDEO,
1318 'mime' => 'application/ogg',
1319 'metadata' => serialize( [] ),
1320 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1321 'fileExists' => true
1322 ], $this->db->timestamp( '20010115123500' ), $user );
1323
1324 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1325 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1326 'size' => 12345,
1327 'width' => 0,
1328 'height' => 0,
1329 'bits' => 0,
1330 'media_type' => MEDIATYPE_AUDIO,
1331 'mime' => 'application/ogg',
1332 'metadata' => serialize( [] ),
1333 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1334 'fileExists' => true
1335 ], $this->db->timestamp( '20010115123500' ), $user );
1336
1337 # A DjVu file
1338 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1339 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1340 'size' => 3249,
1341 'width' => 2480,
1342 'height' => 3508,
1343 'bits' => 0,
1344 'media_type' => MEDIATYPE_BITMAP,
1345 'mime' => 'image/vnd.djvu',
1346 'metadata' => '<?xml version="1.0" ?>
1347 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1348 <DjVuXML>
1349 <HEAD></HEAD>
1350 <BODY><OBJECT height="3508" width="2480">
1351 <PARAM name="DPI" value="300" />
1352 <PARAM name="GAMMA" value="2.2" />
1353 </OBJECT>
1354 <OBJECT height="3508" width="2480">
1355 <PARAM name="DPI" value="300" />
1356 <PARAM name="GAMMA" value="2.2" />
1357 </OBJECT>
1358 <OBJECT height="3508" width="2480">
1359 <PARAM name="DPI" value="300" />
1360 <PARAM name="GAMMA" value="2.2" />
1361 </OBJECT>
1362 <OBJECT height="3508" width="2480">
1363 <PARAM name="DPI" value="300" />
1364 <PARAM name="GAMMA" value="2.2" />
1365 </OBJECT>
1366 <OBJECT height="3508" width="2480">
1367 <PARAM name="DPI" value="300" />
1368 <PARAM name="GAMMA" value="2.2" />
1369 </OBJECT>
1370 </BODY>
1371 </DjVuXML>',
1372 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1373 'fileExists' => true
1374 ], $this->db->timestamp( '20010115123600' ), $user );
1375
1376 return $this->createTeardownObject( $teardown, $nextTeardown );
1377 }
1378
1379 /**
1380 * Helper for database teardown, called from the teardown closure. Destroy
1381 * the database clone and fix up some things that CloneDatabase doesn't fix.
1382 *
1383 * @todo Move most things here to CloneDatabase
1384 */
1385 private function teardownDatabase() {
1386 $this->checkSetupDone( 'setupDatabase' );
1387
1388 $this->dbClone->destroy();
1389 $this->databaseSetupDone = false;
1390
1391 if ( $this->useTemporaryTables ) {
1392 if ( $this->db->getType() == 'sqlite' ) {
1393 # Under SQLite the searchindex table is virtual and need
1394 # to be explicitly destroyed. See T31912
1395 # See also MediaWikiTestCase::destroyDB()
1396 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1397 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1398 }
1399 # Don't need to do anything
1400 return;
1401 }
1402
1403 $tables = $this->listTables();
1404
1405 foreach ( $tables as $table ) {
1406 if ( $this->db->getType() == 'oracle' ) {
1407 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1408 } else {
1409 $this->db->query( "DROP TABLE `parsertest_$table`" );
1410 }
1411 }
1412
1413 if ( $this->db->getType() == 'oracle' ) {
1414 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1415 }
1416 }
1417
1418 /**
1419 * Upload test files to the backend created by createRepoGroup().
1420 *
1421 * @return callable The teardown callback
1422 */
1423 private function setupUploadBackend() {
1424 global $IP;
1425
1426 $repo = RepoGroup::singleton()->getLocalRepo();
1427 $base = $repo->getZonePath( 'public' );
1428 $backend = $repo->getBackend();
1429 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1430 $backend->store( [
1431 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1432 'dst' => "$base/3/3a/Foobar.jpg"
1433 ] );
1434 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1435 $backend->store( [
1436 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1437 'dst' => "$base/e/ea/Thumb.png"
1438 ] );
1439 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1440 $backend->store( [
1441 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1442 'dst' => "$base/0/09/Bad.jpg"
1443 ] );
1444 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1445 $backend->store( [
1446 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1447 'dst' => "$base/5/5f/LoremIpsum.djvu"
1448 ] );
1449
1450 // No helpful SVG file to copy, so make one ourselves
1451 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1452 '<svg xmlns="http://www.w3.org/2000/svg"' .
1453 ' version="1.1" width="240" height="180"/>';
1454
1455 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1456 $backend->quickCreate( [
1457 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1458 ] );
1459
1460 return function () use ( $backend ) {
1461 if ( $backend instanceof MockFileBackend ) {
1462 // In memory backend, so dont bother cleaning them up.
1463 return;
1464 }
1465 $this->teardownUploadBackend();
1466 };
1467 }
1468
1469 /**
1470 * Remove the dummy uploads directory
1471 */
1472 private function teardownUploadBackend() {
1473 if ( $this->keepUploads ) {
1474 return;
1475 }
1476
1477 $repo = RepoGroup::singleton()->getLocalRepo();
1478 $public = $repo->getZonePath( 'public' );
1479
1480 $this->deleteFiles(
1481 [
1482 "$public/3/3a/Foobar.jpg",
1483 "$public/e/ea/Thumb.png",
1484 "$public/0/09/Bad.jpg",
1485 "$public/5/5f/LoremIpsum.djvu",
1486 "$public/f/ff/Foobar.svg",
1487 "$public/0/00/Video.ogv",
1488 "$public/4/41/Audio.oga",
1489 ]
1490 );
1491 }
1492
1493 /**
1494 * Delete the specified files and their parent directories
1495 * @param array $files File backend URIs mwstore://...
1496 */
1497 private function deleteFiles( $files ) {
1498 // Delete the files
1499 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1500 foreach ( $files as $file ) {
1501 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1502 }
1503
1504 // Delete the parent directories
1505 foreach ( $files as $file ) {
1506 $tmp = FileBackend::parentStoragePath( $file );
1507 while ( $tmp ) {
1508 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1509 break;
1510 }
1511 $tmp = FileBackend::parentStoragePath( $tmp );
1512 }
1513 }
1514 }
1515
1516 /**
1517 * Add articles to the test DB.
1518 *
1519 * @param $articles Article info array from TestFileReader
1520 */
1521 public function addArticles( $articles ) {
1522 global $wgContLang;
1523 $setup = [];
1524 $teardown = [];
1525
1526 // Be sure ParserTestRunner::addArticle has correct language set,
1527 // so that system messages get into the right language cache
1528 if ( $wgContLang->getCode() !== 'en' ) {
1529 $setup['wgLanguageCode'] = 'en';
1530 $setup['wgContLang'] = Language::factory( 'en' );
1531 }
1532
1533 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1534 $this->appendNamespaceSetup( $setup, $teardown );
1535
1536 // wgCapitalLinks obviously needs initialisation
1537 $setup['wgCapitalLinks'] = true;
1538
1539 $teardown[] = $this->executeSetupSnippets( $setup );
1540
1541 foreach ( $articles as $info ) {
1542 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1543 }
1544
1545 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1546 // due to T144706
1547 ObjectCache::getMainWANInstance()->clearProcessCache();
1548
1549 $this->executeSetupSnippets( $teardown );
1550 }
1551
1552 /**
1553 * Insert a temporary test article
1554 * @param string $name The title, including any prefix
1555 * @param string $text The article text
1556 * @param string $file The input file name
1557 * @param int|string $line The input line number, for reporting errors
1558 * @throws Exception
1559 * @throws MWException
1560 */
1561 private function addArticle( $name, $text, $file, $line ) {
1562 $text = self::chomp( $text );
1563 $name = self::chomp( $name );
1564
1565 $title = Title::newFromText( $name );
1566 wfDebug( __METHOD__ . ": adding $name" );
1567
1568 if ( is_null( $title ) ) {
1569 throw new MWException( "invalid title '$name' at $file:$line\n" );
1570 }
1571
1572 $page = WikiPage::factory( $title );
1573 $page->loadPageData( 'fromdbmaster' );
1574
1575 if ( $page->exists() ) {
1576 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1577 }
1578
1579 // Use mock parser, to make debugging of actual parser tests simpler.
1580 // But initialise the MessageCache clone first, don't let MessageCache
1581 // get a reference to the mock object.
1582 MessageCache::singleton()->getParser();
1583 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser ] );
1584 $status = $page->doEditContent(
1585 ContentHandler::makeContent( $text, $title ),
1586 '',
1587 EDIT_NEW | EDIT_INTERNAL
1588 );
1589 $restore();
1590
1591 if ( !$status->isOK() ) {
1592 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1593 }
1594
1595 // The RepoGroup cache is invalidated by the creation of file redirects
1596 if ( $title->inNamespace( NS_FILE ) ) {
1597 RepoGroup::singleton()->clearCache( $title );
1598 }
1599 }
1600
1601 /**
1602 * Check if a hook is installed
1603 *
1604 * @param string $name
1605 * @return bool True if tag hook is present
1606 */
1607 public function requireHook( $name ) {
1608 global $wgParser;
1609
1610 $wgParser->firstCallInit(); // make sure hooks are loaded.
1611 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1612 return true;
1613 } else {
1614 $this->recorder->warning( " This test suite requires the '$name' hook " .
1615 "extension, skipping." );
1616 return false;
1617 }
1618 }
1619
1620 /**
1621 * Check if a function hook is installed
1622 *
1623 * @param string $name
1624 * @return bool True if function hook is present
1625 */
1626 public function requireFunctionHook( $name ) {
1627 global $wgParser;
1628
1629 $wgParser->firstCallInit(); // make sure hooks are loaded.
1630
1631 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1632 return true;
1633 } else {
1634 $this->recorder->warning( " This test suite requires the '$name' function " .
1635 "hook extension, skipping." );
1636 return false;
1637 }
1638 }
1639
1640 /**
1641 * Check if a transparent tag hook is installed
1642 *
1643 * @param string $name
1644 * @return bool True if function hook is present
1645 */
1646 public function requireTransparentHook( $name ) {
1647 global $wgParser;
1648
1649 $wgParser->firstCallInit(); // make sure hooks are loaded.
1650
1651 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1652 return true;
1653 } else {
1654 $this->recorder->warning( " This test suite requires the '$name' transparent " .
1655 "hook extension, skipping.\n" );
1656 return false;
1657 }
1658 }
1659
1660 /**
1661 * Fake constant timestamp to make sure time-related parser
1662 * functions give a persistent value.
1663 *
1664 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1665 * - Parser::preSaveTransform (via ParserOptions)
1666 */
1667 private function getFakeTimestamp() {
1668 // parsed as '1970-01-01T00:02:03Z'
1669 return 123;
1670 }
1671 }