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