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