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