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