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