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