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