MediaWiki REL1_31
ParserTestRunner.php
Go to the documentation of this file.
1<?php
30use Wikimedia\ScopedCallback;
31use Wikimedia\TestingAccessWrapper;
32
37
44 private static $coreTestFiles = [
45 'parserTests.txt',
46 'extraParserTests.txt',
47 ];
48
52 private $useTemporaryTables = true;
53
57 private $setupDone = [
58 'staticSetup' => false,
59 'perTestSetup' => false,
60 'setupDatabase' => false,
61 'setDatabase' => false,
62 'setupUploads' => false,
63 ];
64
69 private $db;
70
75 private $dbClone;
76
80 private $tidySupport;
81
85 private $tidyDriver = null;
86
90 private $recorder;
91
97 private $uploadDir = null;
98
104
109 private $regex;
110
117
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
167 public static function getParserTestFiles() {
168 global $wgParserTestFiles;
169
170 // Add core test files
171 $files = array_map( function ( $item ) {
172 return __DIR__ . "/$item";
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 ) {
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
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.
286 $teardown[] = function () {
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 () {
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 () {
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
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;
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
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;
470 }
471 }
472 return function () use ( $saved ) {
473 $this->executeSetupSnippets( $saved );
474 };
475 }
476
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
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
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
539 public function isSetupDone( $funcName ) {
540 return isset( $this->setupDone[$funcName] ) ? $this->setupDone[$funcName] : false;
541 }
542
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 // Reset the service in case any other tests already cached some prefixes.
619 MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
620
621 return function () {
622 // Tear down
623 Hooks::clear( 'InterwikiLoadPrefix' );
624 MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
625 };
626 }
627
632 private function resetTitleServices() {
633 $services = MediaWikiServices::getInstance();
634 $services->resetServiceForTesting( 'TitleFormatter' );
635 $services->resetServiceForTesting( 'TitleParser' );
636 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
637 $services->resetServiceForTesting( 'LinkRenderer' );
638 $services->resetServiceForTesting( 'LinkRendererFactory' );
639 }
640
646 public static function chomp( $s ) {
647 if ( substr( $s, -1 ) === "\n" ) {
648 return substr( $s, 0, -1 );
649 } else {
650 return $s;
651 }
652 }
653
667 public function runTestsFromFiles( $filenames ) {
668 $ok = false;
669
670 $teardownGuard = $this->staticSetup();
671 $teardownGuard = $this->setupDatabase( $teardownGuard );
672 $teardownGuard = $this->setupUploads( $teardownGuard );
673
674 $this->recorder->start();
675 try {
676 $ok = true;
677
678 foreach ( $filenames as $filename ) {
679 $testFileInfo = TestFileReader::read( $filename, [
680 'runDisabled' => $this->runDisabled,
681 'runParsoid' => $this->runParsoid,
682 'regex' => $this->regex ] );
683
684 // Don't start the suite if there are no enabled tests in the file
685 if ( !$testFileInfo['tests'] ) {
686 continue;
687 }
688
689 $this->recorder->startSuite( $filename );
690 $ok = $this->runTests( $testFileInfo ) && $ok;
691 $this->recorder->endSuite( $filename );
692 }
693
694 $this->recorder->report();
695 } catch ( DBError $e ) {
696 $this->recorder->warning( $e->getMessage() );
697 }
698 $this->recorder->end();
699
700 ScopedCallback::consume( $teardownGuard );
701
702 return $ok;
703 }
704
711 public function meetsRequirements( $requirements ) {
712 foreach ( $requirements as $requirement ) {
713 switch ( $requirement['type'] ) {
714 case 'hook':
715 $ok = $this->requireHook( $requirement['name'] );
716 break;
717 case 'functionHook':
718 $ok = $this->requireFunctionHook( $requirement['name'] );
719 break;
720 case 'transparentHook':
721 $ok = $this->requireTransparentHook( $requirement['name'] );
722 break;
723 }
724 if ( !$ok ) {
725 return false;
726 }
727 }
728 return true;
729 }
730
738 public function runTests( $testFileInfo ) {
739 $ok = true;
740
741 $this->checkSetupDone( 'staticSetup' );
742
743 // Don't add articles from the file if there are no enabled tests from the file
744 if ( !$testFileInfo['tests'] ) {
745 return true;
746 }
747
748 // If any requirements are not met, mark all tests from the file as skipped
749 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
750 foreach ( $testFileInfo['tests'] as $test ) {
751 $this->recorder->startTest( $test );
752 $this->recorder->skipped( $test, 'required extension not enabled' );
753 }
754 return true;
755 }
756
757 // Add articles
758 $this->addArticles( $testFileInfo['articles'] );
759
760 // Run tests
761 foreach ( $testFileInfo['tests'] as $test ) {
762 $this->recorder->startTest( $test );
763 $result =
764 $this->runTest( $test );
765 if ( $result !== false ) {
766 $ok = $ok && $result->isSuccess();
767 $this->recorder->record( $test, $result );
768 }
769 }
770
771 return $ok;
772 }
773
780 function getParser( $preprocessor = null ) {
781 global $wgParserConf;
782
783 $class = $wgParserConf['class'];
784 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
786
787 return $parser;
788 }
789
807 public function runTest( $test ) {
808 wfDebug( __METHOD__.": running {$test['desc']}" );
809 $opts = $this->parseOptions( $test['options'] );
810 $teardownGuard = $this->perTestSetup( $test );
811
813 $user = $context->getUser();
814 $options = ParserOptions::newFromContext( $context );
815 $options->setTimestamp( $this->getFakeTimestamp() );
816
817 if ( isset( $opts['tidy'] ) ) {
818 if ( !$this->tidySupport->isEnabled() ) {
819 $this->recorder->skipped( $test, 'tidy extension is not installed' );
820 return false;
821 } else {
822 $options->setTidy( true );
823 }
824 }
825
826 if ( isset( $opts['title'] ) ) {
827 $titleText = $opts['title'];
828 } else {
829 $titleText = 'Parser test';
830 }
831
832 $local = isset( $opts['local'] );
833 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
834 $parser = $this->getParser( $preprocessor );
835 $title = Title::newFromText( $titleText );
836
837 if ( isset( $opts['styletag'] ) ) {
838 // For testing the behavior of <style> (including those deduplicated
839 // into <link> tags), add tag hooks to allow them to be generated.
840 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
841 $marker = Parser::MARKER_PREFIX . '-style-' . md5( $content ) . Parser::MARKER_SUFFIX;
842 $parser->mStripState->addNoWiki( $marker, $content );
843 return Html::inlineStyle( $marker, 'all', $attributes );
844 } );
845 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
846 return Html::element( 'link', $attributes );
847 } );
848 }
849
850 if ( isset( $opts['pst'] ) ) {
851 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
852 $output = $parser->getOutput();
853 } elseif ( isset( $opts['msg'] ) ) {
854 $out = $parser->transformMsg( $test['input'], $options, $title );
855 } elseif ( isset( $opts['section'] ) ) {
856 $section = $opts['section'];
857 $out = $parser->getSection( $test['input'], $section );
858 } elseif ( isset( $opts['replace'] ) ) {
859 $section = $opts['replace'][0];
860 $replace = $opts['replace'][1];
861 $out = $parser->replaceSection( $test['input'], $section, $replace );
862 } elseif ( isset( $opts['comment'] ) ) {
863 $out = Linker::formatComment( $test['input'], $title, $local );
864 } elseif ( isset( $opts['preload'] ) ) {
865 $out = $parser->getPreloadText( $test['input'], $title, $options );
866 } else {
867 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
868 $out = $output->getText( [
869 'allowTOC' => !isset( $opts['notoc'] ),
870 'unwrap' => !isset( $opts['wrap'] ),
871 ] );
872 if ( isset( $opts['tidy'] ) ) {
873 $out = preg_replace( '/\s+$/', '', $out );
874 }
875
876 if ( isset( $opts['showtitle'] ) ) {
877 if ( $output->getTitleText() ) {
878 $title = $output->getTitleText();
879 }
880
881 $out = "$title\n$out";
882 }
883
884 if ( isset( $opts['showindicators'] ) ) {
885 $indicators = '';
886 foreach ( $output->getIndicators() as $id => $content ) {
887 $indicators .= "$id=$content\n";
888 }
889 $out = $indicators . $out;
890 }
891
892 if ( isset( $opts['ill'] ) ) {
893 $out = implode( ' ', $output->getLanguageLinks() );
894 } elseif ( isset( $opts['cat'] ) ) {
895 $out = '';
896 foreach ( $output->getCategories() as $name => $sortkey ) {
897 if ( $out !== '' ) {
898 $out .= "\n";
899 }
900 $out .= "cat=$name sort=$sortkey";
901 }
902 }
903 }
904
905 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
906 $actualFlags = array_keys( TestingAccessWrapper::newFromObject( $output )->mFlags );
907 sort( $actualFlags );
908 $out .= "\nflags=" . implode( ', ', $actualFlags );
909 }
910
911 ScopedCallback::consume( $teardownGuard );
912
913 $expected = $test['result'];
914 if ( count( $this->normalizationFunctions ) ) {
916 $test['expected'], $this->normalizationFunctions );
917 $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
918 }
919
920 $testResult = new ParserTestResult( $test, $expected, $out );
921 return $testResult;
922 }
923
931 private static function getOptionValue( $key, $opts, $default ) {
932 $key = strtolower( $key );
933
934 if ( isset( $opts[$key] ) ) {
935 return $opts[$key];
936 } else {
937 return $default;
938 }
939 }
940
948 private function parseOptions( $instring ) {
949 $opts = [];
950 // foo
951 // foo=bar
952 // foo="bar baz"
953 // foo=[[bar baz]]
954 // foo=bar,"baz quux"
955 // foo={...json...}
956 $defs = '(?(DEFINE)
957 (?<qstr> # Quoted string
958 "
959 (?:[^\\\\"] | \\\\.)*
960 "
961 )
962 (?<json>
963 \{ # Open bracket
964 (?:
965 [^"{}] | # Not a quoted string or object, or
966 (?&qstr) | # A quoted string, or
967 (?&json) # A json object (recursively)
968 )*
969 \} # Close bracket
970 )
971 (?<value>
972 (?:
973 (?&qstr) # Quoted val
974 |
975 \[\[
976 [^]]* # Link target
977 \]\]
978 |
979 [\w-]+ # Plain word
980 |
981 (?&json) # JSON object
982 )
983 )
984 )';
985 $regex = '/' . $defs . '\b
986 (?<k>[\w-]+) # Key
987 \b
988 (?:\s*
989 = # First sub-value
990 \s*
991 (?<v>
992 (?&value)
993 (?:\s*
994 , # Sub-vals 1..N
995 \s*
996 (?&value)
997 )*
998 )
999 )?
1000 /x';
1001 $valueregex = '/' . $defs . '(?&value)/x';
1002
1003 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1004 foreach ( $matches as $bits ) {
1005 $key = strtolower( $bits['k'] );
1006 if ( !isset( $bits['v'] ) ) {
1007 $opts[$key] = true;
1008 } else {
1009 preg_match_all( $valueregex, $bits['v'], $vmatches );
1010 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1011 if ( count( $opts[$key] ) == 1 ) {
1012 $opts[$key] = $opts[$key][0];
1013 }
1014 }
1015 }
1016 }
1017 return $opts;
1018 }
1019
1020 private function cleanupOption( $opt ) {
1021 if ( substr( $opt, 0, 1 ) == '"' ) {
1022 return stripcslashes( substr( $opt, 1, -1 ) );
1023 }
1024
1025 if ( substr( $opt, 0, 2 ) == '[[' ) {
1026 return substr( $opt, 2, -2 );
1027 }
1028
1029 if ( substr( $opt, 0, 1 ) == '{' ) {
1030 return FormatJson::decode( $opt, true );
1031 }
1032 return $opt;
1033 }
1034
1044 public function perTestSetup( $test, $nextTeardown = null ) {
1045 $teardown = [];
1046
1047 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1048 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1049
1050 $opts = $this->parseOptions( $test['options'] );
1051 $config = $test['config'];
1052
1053 // Find out values for some special options.
1054 $langCode =
1055 self::getOptionValue( 'language', $opts, 'en' );
1056 $variant =
1057 self::getOptionValue( 'variant', $opts, false );
1058 $maxtoclevel =
1059 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1060 $linkHolderBatchSize =
1061 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1062
1063 // Default to fallback skin, but allow it to be overridden
1064 $skin = self::getOptionValue( 'skin', $opts, 'fallback' );
1065
1066 $setup = [
1067 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
1068 'wgLanguageCode' => $langCode,
1069 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
1070 'wgNamespacesWithSubpages' => array_fill_keys(
1071 MWNamespace::getValidNamespaces(), isset( $opts['subpage'] )
1072 ),
1073 'wgMaxTocLevel' => $maxtoclevel,
1074 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1075 'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
1076 'wgDefaultLanguageVariant' => $variant,
1077 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1078 // Set as a JSON object like:
1079 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1080 'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1081 + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1082 // Test with legacy encoding by default until HTML5 is very stable and default
1083 'wgFragmentMode' => [ 'legacy' ],
1084 ];
1085
1086 if ( $config ) {
1087 $configLines = explode( "\n", $config );
1088
1089 foreach ( $configLines as $line ) {
1090 list( $var, $value ) = explode( '=', $line, 2 );
1091 $setup[$var] = eval( "return $value;" );
1092 }
1093 }
1094
1096 Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1097
1098 // Create tidy driver
1099 if ( isset( $opts['tidy'] ) ) {
1100 // Cache a driver instance
1101 if ( $this->tidyDriver === null ) {
1102 $this->tidyDriver = MWTidy::factory( $this->tidySupport->getConfig() );
1103 }
1104 $tidy = $this->tidyDriver;
1105 } else {
1106 $tidy = false;
1107 }
1108 MWTidy::setInstance( $tidy );
1109 $teardown[] = function () {
1111 };
1112
1113 // Set content language. This invalidates the magic word cache and title services
1114 $lang = Language::factory( $langCode );
1115 $lang->resetNamespaces();
1116 $setup['wgContLang'] = $lang;
1117 $reset = function () {
1119 $this->resetTitleServices();
1120 };
1121 $setup[] = $reset;
1122 $teardown[] = $reset;
1123
1124 // Make a user object with the same language
1125 $user = new User;
1126 $user->setOption( 'language', $langCode );
1127 $setup['wgLang'] = $lang;
1128
1129 // We (re)set $wgThumbLimits to a single-element array above.
1130 $user->setOption( 'thumbsize', 0 );
1131
1132 $setup['wgUser'] = $user;
1133
1134 // And put both user and language into the context
1136 $context->setUser( $user );
1137 $context->setLanguage( $lang );
1138 // And the skin!
1139 $oldSkin = $context->getSkin();
1140 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
1141 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1142 $context->setOutput( new OutputPage( $context ) );
1143 $setup['wgOut'] = $context->getOutput();
1144 $teardown[] = function () use ( $context, $oldSkin ) {
1145 // Clear language conversion tables
1146 $wrapper = TestingAccessWrapper::newFromObject(
1147 $context->getLanguage()->getConverter()
1148 );
1149 $wrapper->reloadTables();
1150 // Reset context to the restored globals
1151 $context->setUser( $GLOBALS['wgUser'] );
1152 $context->setLanguage( $GLOBALS['wgContLang'] );
1153 $context->setSkin( $oldSkin );
1154 $context->setOutput( $GLOBALS['wgOut'] );
1155 };
1156
1157 $teardown[] = $this->executeSetupSnippets( $setup );
1158
1159 return $this->createTeardownObject( $teardown, $nextTeardown );
1160 }
1161
1167 private function listTables() {
1169
1170 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1171 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1172 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1173 'site_stats', 'ipblocks', 'image', 'oldimage',
1174 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1175 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1176 'archive', 'user_groups', 'page_props', 'category'
1177 ];
1178
1180 // The new tables for comments are in use
1181 $tables[] = 'comment';
1182 $tables[] = 'revision_comment_temp';
1183 $tables[] = 'image_comment_temp';
1184 }
1185
1187 // The new tables for actors are in use
1188 $tables[] = 'actor';
1189 $tables[] = 'revision_actor_temp';
1190 }
1191
1192 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1193 array_push( $tables, 'searchindex' );
1194 }
1195
1196 // Allow extensions to add to the list of tables to duplicate;
1197 // may be necessary if they hook into page save or other code
1198 // which will require them while running tests.
1199 Hooks::run( 'ParserTestTables', [ &$tables ] );
1200
1201 return $tables;
1202 }
1203
1204 public function setDatabase( IDatabase $db ) {
1205 $this->db = $db;
1206 $this->setupDone['setDatabase'] = true;
1207 }
1208
1226 public function setupDatabase( $nextTeardown = null ) {
1227 global $wgDBprefix;
1228
1229 $this->db = wfGetDB( DB_MASTER );
1230 $dbType = $this->db->getType();
1231
1232 if ( $dbType == 'oracle' ) {
1233 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1234 } else {
1235 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1236 }
1237 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1238 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1239 }
1240
1241 $teardown = [];
1242
1243 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1244
1245 # CREATE TEMPORARY TABLE breaks if there is more than one server
1246 if ( wfGetLB()->getServerCount() != 1 ) {
1247 $this->useTemporaryTables = false;
1248 }
1249
1250 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1251 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1252
1253 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1254 $this->dbClone->useTemporaryTables( $temporary );
1255 $this->dbClone->cloneTableStructure();
1256
1257 if ( $dbType == 'oracle' ) {
1258 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1259 # Insert 0 user to prevent FK violations
1260
1261 # Anonymous user
1262 $this->db->insert( 'user', [
1263 'user_id' => 0,
1264 'user_name' => 'Anonymous' ] );
1265 }
1266
1267 $teardown[] = function () {
1268 $this->teardownDatabase();
1269 };
1270
1271 // Wipe some DB query result caches on setup and teardown
1272 $reset = function () {
1273 LinkCache::singleton()->clear();
1274
1275 // Clear the message cache
1276 MessageCache::singleton()->clear();
1277 };
1278 $reset();
1279 $teardown[] = $reset;
1280 return $this->createTeardownObject( $teardown, $nextTeardown );
1281 }
1282
1291 public function setupUploads( $nextTeardown = null ) {
1292 $teardown = [];
1293
1294 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1295 $teardown[] = $this->markSetupDone( 'setupUploads' );
1296
1297 // Create the files in the upload directory (or pretend to create them
1298 // in a MockFileBackend). Append teardown callback.
1299 $teardown[] = $this->setupUploadBackend();
1300
1301 // Create a user
1302 $user = User::createNew( 'WikiSysop' );
1303
1304 // Register the uploads in the database
1305
1306 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1307 # note that the size/width/height/bits/etc of the file
1308 # are actually set by inspecting the file itself; the arguments
1309 # to recordUpload2 have no effect. That said, we try to make things
1310 # match up so it is less confusing to readers of the code & tests.
1311 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1312 'size' => 7881,
1313 'width' => 1941,
1314 'height' => 220,
1315 'bits' => 8,
1316 'media_type' => MEDIATYPE_BITMAP,
1317 'mime' => 'image/jpeg',
1318 'metadata' => serialize( [] ),
1319 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1320 'fileExists' => true
1321 ], $this->db->timestamp( '20010115123500' ), $user );
1322
1323 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1324 # again, note that size/width/height below are ignored; see above.
1325 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1326 'size' => 22589,
1327 'width' => 135,
1328 'height' => 135,
1329 'bits' => 8,
1330 'media_type' => MEDIATYPE_BITMAP,
1331 'mime' => 'image/png',
1332 'metadata' => serialize( [] ),
1333 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1334 'fileExists' => true
1335 ], $this->db->timestamp( '20130225203040' ), $user );
1336
1337 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1338 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1339 'size' => 12345,
1340 'width' => 240,
1341 'height' => 180,
1342 'bits' => 0,
1343 'media_type' => MEDIATYPE_DRAWING,
1344 'mime' => 'image/svg+xml',
1345 'metadata' => serialize( [] ),
1346 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1347 'fileExists' => true
1348 ], $this->db->timestamp( '20010115123500' ), $user );
1349
1350 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1351 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1352 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1353 'size' => 12345,
1354 'width' => 320,
1355 'height' => 240,
1356 'bits' => 24,
1357 'media_type' => MEDIATYPE_BITMAP,
1358 'mime' => 'image/jpeg',
1359 'metadata' => serialize( [] ),
1360 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1361 'fileExists' => true
1362 ], $this->db->timestamp( '20010115123500' ), $user );
1363
1364 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1365 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1366 'size' => 12345,
1367 'width' => 320,
1368 'height' => 240,
1369 'bits' => 0,
1370 'media_type' => MEDIATYPE_VIDEO,
1371 'mime' => 'application/ogg',
1372 'metadata' => serialize( [] ),
1373 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1374 'fileExists' => true
1375 ], $this->db->timestamp( '20010115123500' ), $user );
1376
1377 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1378 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1379 'size' => 12345,
1380 'width' => 0,
1381 'height' => 0,
1382 'bits' => 0,
1383 'media_type' => MEDIATYPE_AUDIO,
1384 'mime' => 'application/ogg',
1385 'metadata' => serialize( [] ),
1386 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1387 'fileExists' => true
1388 ], $this->db->timestamp( '20010115123500' ), $user );
1389
1390 # A DjVu file
1391 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1392 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1393 'size' => 3249,
1394 'width' => 2480,
1395 'height' => 3508,
1396 'bits' => 0,
1397 'media_type' => MEDIATYPE_BITMAP,
1398 'mime' => 'image/vnd.djvu',
1399 'metadata' => '<?xml version="1.0" ?>
1400<!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1401<DjVuXML>
1402<HEAD></HEAD>
1403<BODY><OBJECT height="3508" width="2480">
1404<PARAM name="DPI" value="300" />
1405<PARAM name="GAMMA" value="2.2" />
1406</OBJECT>
1407<OBJECT height="3508" width="2480">
1408<PARAM name="DPI" value="300" />
1409<PARAM name="GAMMA" value="2.2" />
1410</OBJECT>
1411<OBJECT height="3508" width="2480">
1412<PARAM name="DPI" value="300" />
1413<PARAM name="GAMMA" value="2.2" />
1414</OBJECT>
1415<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</BODY>
1424</DjVuXML>',
1425 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1426 'fileExists' => true
1427 ], $this->db->timestamp( '20010115123600' ), $user );
1428
1429 return $this->createTeardownObject( $teardown, $nextTeardown );
1430 }
1431
1438 private function teardownDatabase() {
1439 $this->checkSetupDone( 'setupDatabase' );
1440
1441 $this->dbClone->destroy();
1442 $this->databaseSetupDone = false;
1443
1444 if ( $this->useTemporaryTables ) {
1445 if ( $this->db->getType() == 'sqlite' ) {
1446 # Under SQLite the searchindex table is virtual and need
1447 # to be explicitly destroyed. See T31912
1448 # See also MediaWikiTestCase::destroyDB()
1449 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1450 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1451 }
1452 # Don't need to do anything
1453 return;
1454 }
1455
1456 $tables = $this->listTables();
1457
1458 foreach ( $tables as $table ) {
1459 if ( $this->db->getType() == 'oracle' ) {
1460 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1461 } else {
1462 $this->db->query( "DROP TABLE `parsertest_$table`" );
1463 }
1464 }
1465
1466 if ( $this->db->getType() == 'oracle' ) {
1467 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1468 }
1469 }
1470
1476 private function setupUploadBackend() {
1477 global $IP;
1478
1479 $repo = RepoGroup::singleton()->getLocalRepo();
1480 $base = $repo->getZonePath( 'public' );
1481 $backend = $repo->getBackend();
1482 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1483 $backend->store( [
1484 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1485 'dst' => "$base/3/3a/Foobar.jpg"
1486 ] );
1487 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1488 $backend->store( [
1489 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1490 'dst' => "$base/e/ea/Thumb.png"
1491 ] );
1492 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1493 $backend->store( [
1494 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1495 'dst' => "$base/0/09/Bad.jpg"
1496 ] );
1497 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1498 $backend->store( [
1499 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1500 'dst' => "$base/5/5f/LoremIpsum.djvu"
1501 ] );
1502
1503 // No helpful SVG file to copy, so make one ourselves
1504 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1505 '<svg xmlns="http://www.w3.org/2000/svg"' .
1506 ' version="1.1" width="240" height="180"/>';
1507
1508 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1509 $backend->quickCreate( [
1510 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1511 ] );
1512
1513 return function () use ( $backend ) {
1514 if ( $backend instanceof MockFileBackend ) {
1515 // In memory backend, so dont bother cleaning them up.
1516 return;
1517 }
1518 $this->teardownUploadBackend();
1519 };
1520 }
1521
1525 private function teardownUploadBackend() {
1526 if ( $this->keepUploads ) {
1527 return;
1528 }
1529
1530 $repo = RepoGroup::singleton()->getLocalRepo();
1531 $public = $repo->getZonePath( 'public' );
1532
1533 $this->deleteFiles(
1534 [
1535 "$public/3/3a/Foobar.jpg",
1536 "$public/e/ea/Thumb.png",
1537 "$public/0/09/Bad.jpg",
1538 "$public/5/5f/LoremIpsum.djvu",
1539 "$public/f/ff/Foobar.svg",
1540 "$public/0/00/Video.ogv",
1541 "$public/4/41/Audio.oga",
1542 ]
1543 );
1544 }
1545
1550 private function deleteFiles( $files ) {
1551 // Delete the files
1552 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1553 foreach ( $files as $file ) {
1554 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1555 }
1556
1557 // Delete the parent directories
1558 foreach ( $files as $file ) {
1559 $tmp = FileBackend::parentStoragePath( $file );
1560 while ( $tmp ) {
1561 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1562 break;
1563 }
1564 $tmp = FileBackend::parentStoragePath( $tmp );
1565 }
1566 }
1567 }
1568
1574 public function addArticles( $articles ) {
1575 global $wgContLang;
1576 $setup = [];
1577 $teardown = [];
1578
1579 // Be sure ParserTestRunner::addArticle has correct language set,
1580 // so that system messages get into the right language cache
1581 if ( $wgContLang->getCode() !== 'en' ) {
1582 $setup['wgLanguageCode'] = 'en';
1583 $setup['wgContLang'] = Language::factory( 'en' );
1584 }
1585
1586 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1587 $this->appendNamespaceSetup( $setup, $teardown );
1588
1589 // wgCapitalLinks obviously needs initialisation
1590 $setup['wgCapitalLinks'] = true;
1591
1592 $teardown[] = $this->executeSetupSnippets( $setup );
1593
1594 foreach ( $articles as $info ) {
1595 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1596 }
1597
1598 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1599 // due to T144706
1600 ObjectCache::getMainWANInstance()->clearProcessCache();
1601
1602 $this->executeSetupSnippets( $teardown );
1603 }
1604
1614 private function addArticle( $name, $text, $file, $line ) {
1615 $text = self::chomp( $text );
1616 $name = self::chomp( $name );
1617
1618 $title = Title::newFromText( $name );
1619 wfDebug( __METHOD__ . ": adding $name" );
1620
1621 if ( is_null( $title ) ) {
1622 throw new MWException( "invalid title '$name' at $file:$line\n" );
1623 }
1624
1625 $newContent = ContentHandler::makeContent( $text, $title );
1626
1627 $page = WikiPage::factory( $title );
1628 $page->loadPageData( 'fromdbmaster' );
1629
1630 if ( $page->exists() ) {
1631 $content = $page->getContent( Revision::RAW );
1632 // Only reject the title, if the content/content model is different.
1633 // This makes it easier to create Template:(( or Template:)) in different extensions
1634 if ( $newContent->equals( $content ) ) {
1635 return;
1636 }
1637 throw new MWException(
1638 "duplicate article '$name' with different content at $file:$line\n"
1639 );
1640 }
1641
1642 // Use mock parser, to make debugging of actual parser tests simpler.
1643 // But initialise the MessageCache clone first, don't let MessageCache
1644 // get a reference to the mock object.
1645 MessageCache::singleton()->getParser();
1646 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser ] );
1647 try {
1648 $status = $page->doEditContent(
1649 $newContent,
1650 '',
1652 );
1653 } finally {
1654 $restore();
1655 }
1656
1657 if ( !$status->isOK() ) {
1658 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1659 }
1660
1661 // The RepoGroup cache is invalidated by the creation of file redirects
1662 if ( $title->inNamespace( NS_FILE ) ) {
1663 RepoGroup::singleton()->clearCache( $title );
1664 }
1665 }
1666
1673 public function requireHook( $name ) {
1674 global $wgParser;
1675
1676 $wgParser->firstCallInit(); // make sure hooks are loaded.
1677 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1678 return true;
1679 } else {
1680 $this->recorder->warning( " This test suite requires the '$name' hook " .
1681 "extension, skipping." );
1682 return false;
1683 }
1684 }
1685
1692 public function requireFunctionHook( $name ) {
1693 global $wgParser;
1694
1695 $wgParser->firstCallInit(); // make sure hooks are loaded.
1696
1697 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1698 return true;
1699 } else {
1700 $this->recorder->warning( " This test suite requires the '$name' function " .
1701 "hook extension, skipping." );
1702 return false;
1703 }
1704 }
1705
1712 public function requireTransparentHook( $name ) {
1713 global $wgParser;
1714
1715 $wgParser->firstCallInit(); // make sure hooks are loaded.
1716
1717 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1718 return true;
1719 } else {
1720 $this->recorder->warning( " This test suite requires the '$name' transparent " .
1721 "hook extension, skipping.\n" );
1722 return false;
1723 }
1724 }
1725
1733 private function getFakeTimestamp() {
1734 // parsed as '1970-01-01T00:02:03Z'
1735 return 123;
1736 }
1737}
serialize()
$GLOBALS['IP']
$wgObjectCaches
Advanced object cache configuration.
$wgFileBackends
File backend structure configuration.
$wgDBprefix
Table name prefix.
$wgParserTestFiles
Parser test suite files to be run by parserTests.php when no specific filename is passed to it.
$wgParserConf
Parser configuration.
int $wgCommentTableSchemaMigrationStage
Comment table schema migration stage.
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTempDir()
Tries to get the system directory for temporary files.
wfGetLB( $wiki=false)
Get a load balancer object.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfLocalFile( $title)
Get an object referring to a locally registered file.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
$wgParser
Definition Setup.php:917
$line
Definition cdb.php:59
Class for a file system (FS) based file backend.
static parentStoragePath( $storagePath)
Get the parent storage directory of a storage path.
Simple store for keeping values in an associative array for the current process.
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition Linker.php:1109
static destroySingletons()
Destroy the singleton instances.
MediaWiki exception.
static factory(array $config)
Create a new Tidy driver object from configuration.
Definition MWTidy.php:103
static setInstance( $instance)
Set the driver to be used.
Definition MWTidy.php:135
static destroySingleton()
Destroy the current singleton instance.
Definition MWTidy.php:142
static clearCache()
Clear the self::$mObjects variable For use in parser tests.
Class to construct MediaHandler objects.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static destroyInstance()
Destroy the singleton instance.
static singleton()
Get the signleton instance of this class.
Class simulating a backend store.
This class should be covered by a general architecture document which does not exist as of January 20...
A parser used during article insertion which does nothing, to avoid unnecessary log noise and other i...
Represent the result of a parser test.
TidySupport $tidySupport
listTables()
List of temporary tables to create, without prefix.
runTestsFromFiles( $filenames)
Run a series of tests listed in the given text files.
staticSetup( $nextTeardown=null)
Do any setup which can be done once for all tests, independent of test options, except for database s...
markSetupDone( $funcName)
Set a setupDone flag to indicate that setup has been done, and return the teardown closure.
string $regex
A complete regex for filtering tests.
runTest( $test)
Run a given wikitext input through a freshly-constructed wiki parser, and compare the output against ...
setupUploads( $nextTeardown=null)
Add data about uploads to the new test DB, and set up the upload directory.
createRepoGroup()
Create a RepoGroup object appropriate for the current configuration.
createTeardownObject( $teardown, $nextTeardown=null)
Take a setup array in the same format as the one given to executeSetupSnippets(), and return a Scoped...
teardownUploadBackend()
Remove the dummy uploads directory.
static array $coreTestFiles
MediaWiki core parser test files, paths will be prefixed with DIR .
TestRecorder $recorder
string null $uploadDir
The upload directory, or null to not set up an upload directory.
setupDatabase( $nextTeardown=null)
Set up temporary DB tables.
checkSetupDone( $funcName, $funcName2=null)
Ensure a given setup stage has been done, throw an exception if it has not.
static getParserTestFiles()
Get list of filenames to extension and core parser tests.
requireHook( $name)
Check if a hook is installed.
setDatabase(IDatabase $db)
array $normalizationFunctions
A list of normalization functions to apply to the expected and actual output.
isSetupDone( $funcName)
Determine whether a particular setup function has been run.
resetTitleServices()
Reset the Title-related services that need resetting for each test.
string null $fileBackendName
The name of the file backend to use, or null to use MockFileBackend.
deleteFiles( $files)
Delete the specified files and their parent directories.
static getOptionValue( $key, $opts, $default)
Use a regex to find out the value of an option.
perTestSetup( $test, $nextTeardown=null)
Do any required setup which is dependent on test options.
Database $db
Our connection to the database.
setupInterwikis()
Insert hardcoded interwiki in the lookup table.
__construct(TestRecorder $recorder, $options=[])
requireTransparentHook( $name)
Check if a transparent tag hook is installed.
CloneDatabase $dbClone
Database clone helper.
runTests( $testFileInfo)
Run the tests from a single file.
teardownDatabase()
Helper for database teardown, called from the teardown closure.
requireFunctionHook( $name)
Check if a function hook is installed.
meetsRequirements( $requirements)
Determine whether the current parser has the hooks registered in it that are required by a file read ...
setupUploadBackend()
Upload test files to the backend created by createRepoGroup().
executeSetupSnippets( $setup)
Execute an array in which elements with integer keys are taken to be callable objects,...
addArticles( $articles)
Add articles to the test DB.
getFakeTimestamp()
Fake constant timestamp to make sure time-related parser functions give a persistent value.
static chomp( $s)
Remove last character if it is a newline.
TidyDriverBase $tidyDriver
parseOptions( $instring)
Given the options string, return an associative array of options.
addArticle( $name, $text, $file, $line)
Insert a temporary test article.
getParser( $preprocessor=null)
Get a Parser object.
appendNamespaceSetup(&$setup, &$teardown)
Prioritized list of file repositories.
Definition RepoGroup.php:29
static singleton()
Get a RepoGroup instance.
Definition RepoGroup.php:59
static setSingleton( $instance)
Set the singleton instance to a given object Used by extensions which hook into the Repo chain.
Definition RepoGroup.php:85
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called.
Definition RepoGroup.php:73
static getMain()
Get the RequestContext object associated with the main request.
static read( $file, array $options=[])
Interface to record parser test results.
warning( $message)
Show a warning to the user.
Initialize and detect the tidy support.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:53
setOption( $oname, $val)
Set the given option for a user.
Definition User.php:3241
static createNew( $name, $params=[])
Add a user to the database, return the user object.
Definition User.php:4297
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
do that in ParserLimitReportFormat instead $parser
Definition hooks.txt:2603
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
Definition hooks.txt:2255
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1051
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition hooks.txt:1015
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition hooks.txt:895
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2006
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition hooks.txt:2273
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:864
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:3022
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
returning false will NOT prevent logging $e
Definition hooks.txt:2176
$IP
Definition update.php:3
const EDIT_INTERNAL
Definition Defines.php:169
const NS_FILE
Definition Defines.php:80
const CACHE_DB
Definition Defines.php:113
const MIGRATION_WRITE_BOTH
Definition Defines.php:303
const EDIT_NEW
Definition Defines.php:162
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
const MEDIATYPE_DRAWING
Definition defines.php:30
const MEDIATYPE_VIDEO
Definition defines.php:35
const MEDIATYPE_AUDIO
Definition defines.php:32
const MEDIATYPE_BITMAP
Definition defines.php:28
const DB_MASTER
Definition defines.php:29
if(!isset( $args[0])) $lang