Debian Codegraph @

tests/parser/ParserTestRunner.php

raw symbols SCIP
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 Brooke Vibber <[email protected]>
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
29 use MediaWiki\Content\WikitextContent;
30 use MediaWiki\Context\IContextSource;
31 use MediaWiki\Context\RequestContext;
32 use MediaWiki\HookContainer\HookRunner;
33 use MediaWiki\Html\Html;
34 use MediaWiki\Interwiki\ClassicInterwikiLookup;
35 use MediaWiki\Json\FormatJson;
36 use MediaWiki\Linker\LinkTarget;
37 use MediaWiki\MainConfigNames;
38 use MediaWiki\MediaWikiServices;
39 use MediaWiki\Page\PageReferenceValue;
40 use MediaWiki\Parser\Parser;
41 use MediaWiki\Parser\ParserOptions;
42 use MediaWiki\Parser\ParserOutput;
43 use MediaWiki\Parser\ParserOutputFlags;
44 use MediaWiki\Permissions\UltimateAuthority;
45 use MediaWiki\Registration\ExtensionRegistry;
46 use MediaWiki\Revision\MutableRevisionRecord;
47 use MediaWiki\Revision\RevisionRecord;
48 use MediaWiki\Revision\SlotRecord;
49 use MediaWiki\Title\Title;
50 use MediaWiki\Title\TitleValue;
51 use MediaWiki\User\User;
52 use MediaWiki\User\UserIdentity;
53 use MediaWiki\User\UserIdentityValue;
54 use MediaWiki\Utils\MWTimestamp;
55 use MediaWiki\WikiMap\WikiMap;
56 use Psr\Log\NullLogger;
57 use Wikimedia\Assert\Assert;
58 use Wikimedia\FileBackend\FileBackend;
59 use Wikimedia\FileBackend\FSFileBackend;
60 use Wikimedia\Parsoid\Config\PageConfig;
61 use Wikimedia\Parsoid\Config\SiteConfig;
62 use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
63 use Wikimedia\Parsoid\Core\SelserData;
64 use Wikimedia\Parsoid\DOM\Document;
65 use Wikimedia\Parsoid\Ext\ExtensionModule;
66 use Wikimedia\Parsoid\ParserTests\Article as ParserTestArticle;
67 use Wikimedia\Parsoid\ParserTests\ParserHook as ParsoidParserHook;
68 use Wikimedia\Parsoid\ParserTests\RawHTML as ParsoidRawHTML;
69 use Wikimedia\Parsoid\ParserTests\StyleTag as ParsoidStyleTag;
70 use Wikimedia\Parsoid\ParserTests\Test as ParserTest;
71 use Wikimedia\Parsoid\ParserTests\TestFileReader;
72 use Wikimedia\Parsoid\ParserTests\TestMode as ParserTestMode;
73 use Wikimedia\Parsoid\Parsoid;
74 use Wikimedia\Parsoid\Utils\ContentUtils;
75 use Wikimedia\Parsoid\Utils\DOMCompat;
76 use Wikimedia\Parsoid\Utils\DOMDataUtils;
77 use Wikimedia\Parsoid\Utils\DOMUtils;
78 use Wikimedia\Rdbms\DBError;
79 use Wikimedia\Rdbms\IDatabase;
80 use Wikimedia\Rdbms\IDBAccessObject;
81 use Wikimedia\ScopedCallback;
82 use Wikimedia\TestingAccessWrapper;
83
84 /**
85 * @ingroup Testing
86 */
87 class ParserTestRunner {
88
89 /**
90 * @var array<string,bool> The status of each setup function
91 */
92 private $setupDone = [
93 'staticSetup' => false,
94 'perTestSetup' => false,
95 'setupDatabase' => false,
96 'setupUploads' => false,
97 ];
98
99 /**
100 * @var array (CLI/Config) Options for the test runner
101 * See the constructor for documentation
102 */
103 private $options;
104
105 /**
106 * @var string[] Set of requested test modes
107 */
108 private $requestedTestModes;
109
110 /**
111 * Our connection to the database
112 * @var IDatabase
113 */
114 private $db;
115
116 /**
117 * @var TestRecorder
118 */
119 private $recorder;
120
121 /**
122 * The upload directory, or null to not set up an upload directory
123 *
124 * @var string|null
125 */
126 private $uploadDir = null;
127
128 /**
129 * The name of the file backend to use, or false to use MockFileBackend.
130 * @var string|false
131 */
132 private $fileBackendName;
133
134 /**
135 * A complete regex for filtering tests.
136 * @var string
137 */
138 private $regex;
139
140 /**
141 * A list of normalization functions to apply to the expected and actual
142 * output.
143 * @var string[]
144 */
145 private $normalizationFunctions = [];
146
147 /**
148 * Run disabled parser tests
149 * @var bool
150 */
151 private $runDisabled;
152
153 /**
154 * Disable parse on article insertion
155 * @var bool
156 */
157 private $disableSaveParse;
158
159 /**
160 * Reuse upload directory
161 * @var bool
162 */
163 private $keepUploads;
164
165 /**
166 * Did some Parsoid test pass where it was expected to fail?
167 * This can happen if the test failure is recorded in the -knownFailures.json file
168 * but the test result changed, or functionality changed that causes tests to pass.
169 * @var bool
170 */
171 public $unexpectedTestPasses = false;
172
173 /**
174 * Table name prefix.
175 */
176 public const DB_PREFIX = 'parsertest_';
177
178 private const FILTER_MSG = "Test doesn't match filter";
179
180 /**
181 * Compute the set of valid test runner modes
182 *
183 * @return string[]
184 */
185 public function getRequestedTestModes(): array {
186 return $this->requestedTestModes;
187 }
188
189 /**
190 * @param TestRecorder $recorder
191 * @param array $options
192 * - parsoid (bool) if true, run Parsoid tests
193 * - testFile (string)
194 * If set, the (Parsoid) test file to run tests from.
195 * Currently, only used for CLI PHPUnit test runs
196 * to avoid running every single test file out there.
197 * Legacy parser test runs ignore this option.
198 * - wt2html (bool) If true, run Parsoid wt2html tests
199 * - wt2wt (bool) If true, run Parsoid wt2wt tests
200 * - html2wt (bool) If true, run Parsoid html2wt tests
201 * - html2html (bool) If true, run Parsoid html2html tests
202 * - selser (bool/"noauto")
203 * If true, run Parsoid auto-generated selser tests
204 * If "noauto", run Parsoid manual edit selser tests
205 * - numchanges (int) number of selser edit tests to generate
206 * - changetree (array|null)
207 * If not null, run a Parsoid selser edit test with this changetree
208 * - updateKnownFailures (bool)
209 * If true, *knownFailures.json files are updated
210 * - traceFlags (array)
211 * (Parsoid-only) Flags for tracing different Parsoid stages
212 * - dumpFlags (array)
213 * (Parsoid-only) Flags for dumping various pieces of state
214 * - norm (array)
215 * An array of normalization functions to run on test output
216 * to use in legacy parser test runs
217 * - regex (string) Regex for filtering tests
218 * - run-disabled (bool) If true, run disabled tests
219 * - keep-uploads (bool) If true, reuse upload directory
220 * - file-backend (string|bool)
221 * If false, use MockFileBackend
222 * Else name of the file backend to use
223 * - disable-save-parse (bool) if true, disable parse on article insertion
224 * - update-tests (bool) Update parserTests.txt with results from wt2html fails.
225 *
226 * NOTE: At this time, Parsoid-specific test options are only handled
227 * in PHPUnit mode. A future patch will likely tweak some of this and
228 * support these flags no matter how this test runner is instantiated.
229 */
230 public function __construct( TestRecorder $recorder, $options = [] ) {
231 $this->recorder = $recorder;
232 $this->options = $options + [
233 'keep-uploads' => false,
234 'file-backend' => false,
235 'run-disabled' => false,
236 'disable-save-parse' => false,
237 'upload-dir' => null,
238 'regex' => false,
239 'norm' => [],
240 // Parsoid-specific options
241 'parsoid' => false,
242 'knownFailures' => true,
243 'updateKnownFailures' => false,
244 'changetree' => null,
245 'update-tests' => false,
246 // Options can also match those in ParserTestModes::TEST_MODES
247 // but we don't need to initialize those here; they will be
248 // accessed via $this->requestedTestModes instead.
249 'traceFlags' => [],
250 'dumpFlags' => [],
251 ];
252
253 // Requested test modes are used for Parsoid tests and ignored for
254 // legacy parser tests.
255 $this->requestedTestModes = ParserTestMode::requestedTestModes(
256 $this->options
257 );
258
259 $normFuncs = $this->options['norm'];
260 '@phan-var string[] $normFuncs';
261 foreach ( $normFuncs as $func ) {
262 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
263 $this->normalizationFunctions[] = $func;
264 } else {
265 $this->recorder->warning(
266 "Warning: unknown normalization option \"$func\"\n" );
267 }
268 }
269
270 if ( $this->options['regex'] !== false ) {
271 $this->regex = $this->options['regex'];
272 } else {
273 # Matches anything
274 $this->regex = '//';
275 }
276
277 $this->keepUploads = (bool)$this->options['keep-uploads'];
278 $this->fileBackendName = $this->options['file-backend'];
279 $this->runDisabled = (bool)$this->options['run-disabled'];
280 $this->disableSaveParse = (bool)$this->options['disable-save-parse'];
281 $this->uploadDir = $this->options['upload-dir'];
282 }
283
284 /**
285 * @return array
286 */
287 public function getOptions(): array {
288 return $this->options;
289 }
290
291 /**
292 * Get list of filenames to extension and core parser tests
293 *
294 * @param string[] $dirs
295 * @return string[]
296 */
297 public static function getParserTestFiles( array $dirs = [] ): array {
298 if ( $dirs ) {
299 $ptDirs = [];
300 foreach ( $dirs as $i => $dir ) {
301 if ( !is_dir( $dir ) ) {
302 echo "$dir is not a directory. Skipping it.\n";
303 continue;
304 }
305 $ptDirs["_CLI{$i}_"] = $dir;
306 }
307 } else {
308 // Auto-discover core test files
309 $ptDirs = [ 'core' => __DIR__ ];
310
311 // Auto-discover extension parser tests
312 $registry = ExtensionRegistry::getInstance();
313 foreach ( $registry->getAllThings() as $info ) {
314 $dir = dirname( $info['path'] ) . '/tests/parser';
315 if ( !is_dir( $dir ) ) {
316 continue;
317 }
318 $ptDirs[ $info['name'] ] = $dir;
319 }
320 }
321
322 $files = [];
323 foreach ( $ptDirs as $extName => $dir ) {
324 $counter = 1;
325 $dirIterator = new RecursiveIteratorIterator(
326 new RecursiveDirectoryIterator( $dir )
327 );
328 foreach ( $dirIterator as $fileInfo ) {
329 /** @var SplFileInfo $fileInfo */
330 if ( str_ends_with( $fileInfo->getFilename(), '.txt' ) ) {
331 $name = $extName . '_' . $counter;
332 while ( isset( $files[$name] ) ) {
333 $counter++;
334 $name = $extName . '_' . $counter;
335 }
336 $files[$name] = $fileInfo->getPathname();
337 }
338 }
339 }
340
341 return array_unique( $files );
342 }
343
344 public function getRecorder(): TestRecorder {
345 return $this->recorder;
346 }
347
348 /**
349 * Do any setup which can be done once for all tests, independent of test
350 * options, except for database setup.
351 *
352 * Public setup functions in this class return a ScopedCallback object. When
353 * this object is destroyed by going out of scope, teardown of the
354 * corresponding test setup is performed.
355 *
356 * Teardown objects may be chained by passing a ScopedCallback from a
357 * previous setup stage as the $nextTeardown parameter. This enforces the
358 * convention that teardown actions are taken in reverse order to the
359 * corresponding setup actions. When $nextTeardown is specified, a
360 * ScopedCallback will be returned which first tears down the current
361 * setup stage, and then tears down the previous setup stage which was
362 * specified by $nextTeardown.
363 *
364 * @param ScopedCallback|null $nextTeardown
365 * @return ScopedCallback
366 */
367 public function staticSetup( $nextTeardown = null ) {
368 // A note on coding style:
369
370 // The general idea here is to keep setup code together with
371 // corresponding teardown code, in a fine-grained manner. We have two
372 // arrays: $setup and $teardown. The code snippets in the $setup array
373 // are executed at the end of the method, before it returns, and the
374 // code snippets in the $teardown array are executed in reverse order
375 // when the Wikimedia\ScopedCallback object is consumed.
376
377 // Because it is a common operation to save, set and restore global
378 // variables, we have an additional convention: when the array key of
379 // $setup is a string, the string is taken to be the name of the global
380 // variable, and the element value is taken to be the desired new value.
381
382 // It's acceptable to just do the setup immediately, instead of adding
383 // a closure to $setup, except when the setup action depends on global
384 // variable initialisation being done first. In this case, you have to
385 // append a closure to $setup after the global variable is appended.
386
387 // When you add to setup functions in this class, please keep associated
388 // setup and teardown actions together in the source code, and please
389 // add comments explaining why the setup action is necessary.
390
391 $setup = [];
392 $teardown = [];
393
394 $teardown[] = $this->markSetupDone( 'staticSetup' );
395
396 // Some settings which influence HTML output
397 $setup['wgSitename'] = 'MediaWiki';
398 $setup['wgMetaNamespace'] = "TestWiki";
399 $setup['wgServer'] = 'http://example.org';
400 $setup['wgServerName'] = 'example.org';
401 $setup['wgCapitalLinks'] = true;
402 $setup['wgNoFollowLinks'] = true;
403 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
404 $setup['wgExternalLinkTarget'] = false;
405 $setup['wgLocaltimezone'] = 'UTC';
406 $reset = static function () {
407 MediaWikiServices::getInstance()->resetServiceForTesting( 'UrlUtils' );
408 };
409 $setup[] = $reset;
410 $teardown[] = $reset;
411
412 // Language and variant settings
413 $setup['wgLanguageCode'] = 'en';
414 $setup['wgDisableLangConversion'] = false;
415 $setup['wgDisableTitleConversion'] = false;
416 $setup['wgUsePigLatinVariant'] = false;
417 $this->resetLanguageServices( $setup, $teardown, true );
418
419 // "extra language links"
420 // see https://gerrit.wikimedia.org/r/111390
421 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
422
423 // All FileRepo changes should be done here by injecting services,
424 // there should be no need to change global variables.
425 MediaWikiServices::getInstance()->disableService( 'RepoGroup' );
426 MediaWikiServices::getInstance()->redefineService( 'RepoGroup',
427 function () {
428 return $this->createRepoGroup();
429 }
430 );
431 $teardown[] = static function () {
432 MediaWikiServices::getInstance()->resetServiceForTesting( 'RepoGroup' );
433 };
434
435 // Set up null lock managers
436 $setup['wgLockManagers'] = [ [
437 'name' => 'fsLockManager',
438 'class' => NullLockManager::class,
439 ], [
440 'name' => 'nullLockManager',
441 'class' => NullLockManager::class,
442 ] ];
443 $reset = static function () {
444 MediaWikiServices::getInstance()->resetServiceForTesting( 'LockManagerGroupFactory' );
445 };
446 $setup[] = $reset;
447 $teardown[] = $reset;
448
449 // This allows article insertion into the prefixed DB
450 $setup['wgDefaultExternalStore'] = false;
451
452 // This might slightly reduce memory usage
453 $setup['wgAdaptiveMessageCache'] = true;
454
455 // This is essential and overrides disabling of database messages in TestSetup
456 $setup['wgUseDatabaseMessages'] = true;
457 $reset = static function () {
458 MediaWikiServices::getInstance()->resetServiceForTesting( 'MessageCache' );
459 };
460 $setup[] = $reset;
461 $teardown[] = $reset;
462
463 // It's not necessary to actually convert any files
464 $setup['wgSVGConverter'] = 'null';
465 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
466
467 // Fake constant timestamp
468 $teardown[] = $this->registerHook(
469 'ParserGetVariableValueTs',
470 function ( $parser, &$ts ) {
471 $ts = $this->getFakeTimestamp();
472 return true;
473 }
474 );
475
476 // Fake specific translated language names, for testing {{#language}}
477 $teardown[] = $this->registerHook(
478 'LanguageGetTranslatedLanguageNames',
479 static function ( &$names, $code ) {
480 if ( $code === 'en' || $code === 'simple' ) {
481 $names['ar'] = 'Arabic';
482 $names['de-formal'] = 'German (formal address)';
483 }
484 }
485 );
486
487 $this->appendNamespaceSetup( $setup, $teardown );
488
489 // Set up interwikis and append teardown function
490 $this->appendInterwikiSetup( $setup, $teardown );
491
492 // Set up a mock MediaHandlerFactory
493 MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
494 MediaWikiServices::getInstance()->redefineService(
495 'MediaHandlerFactory',
496 static function ( MediaWikiServices $services ) {
497 $handlers = $services->getMainConfig()->get( MainConfigNames::ParserTestMediaHandlers );
498 return new MediaHandlerFactory(
499 new NullLogger(),
500 $handlers
501 );
502 }
503 );
504 $teardown[] = static function () {
505 MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
506 };
507
508 $teardown[] = $this->executeSetupSnippets( $setup );
509
510 // Schedule teardown snippets in reverse order
511 return $this->createTeardownObject( $teardown, $nextTeardown );
512 }
513
514 private function appendNamespaceSetup( &$setup, &$teardown ) {
515 // Add a namespace shadowing a interwiki link, to test
516 // proper precedence when resolving links. (T53680)
517 $setup['wgExtraNamespaces'] = [
518 100 => 'MemoryAlpha',
519 101 => 'MemoryAlpha_talk'
520 ];
521 // Changing wgExtraNamespaces invalidates caches in NamespaceInfo and any live Language
522 // object, both on setup and teardown
523 $reset = static function () {
524 MediaWikiServices::getInstance()->resetServiceForTesting( 'MainConfig' );
525 MediaWikiServices::getInstance()->resetServiceForTesting( 'NamespaceInfo' );
526 MediaWikiServices::getInstance()->resetServiceForTesting( 'LanguageFactory' );
527 MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
528 MediaWikiServices::getInstance()->resetServiceForTesting( 'LanguageConverterFactory' );
529 // Don't destroy the link cache, because various things hold a
530 // copy of it. Just clear it.
531 MediaWikiServices::getInstance()->getLinkCache()->clear();
532 };
533 $setup[] = $reset;
534 $teardown[] = $reset;
535 }
536
537 /**
538 * Create a RepoGroup object appropriate for the current configuration
539 * @return RepoGroup
540 */
541 protected function createRepoGroup() {
542 if ( $this->uploadDir ) {
543 if ( $this->fileBackendName ) {
544 throw new RuntimeException( 'You cannot specify both use-filebackend and upload-dir' );
545 }
546 $backend = new FSFileBackend( [
547 'name' => 'local-backend',
548 'wikiId' => WikiMap::getCurrentWikiId(),
549 'basePath' => $this->uploadDir,
550 'tmpDirectory' => wfTempDir()
551 ] );
552 } elseif ( $this->fileBackendName ) {
553 global $wgFileBackends;
554 $name = $this->fileBackendName;
555 $useConfig = false;
556 foreach ( $wgFileBackends as $conf ) {
557 if ( $conf['name'] === $name ) {
558 $useConfig = $conf;
559 }
560 }
561 if ( $useConfig === false ) {
562 throw new RuntimeException( "Unable to find file backend \"$name\"" );
563 }
564 $useConfig['name'] = 'local-backend'; // swap name
565 unset( $useConfig['lockManager'] );
566 $class = $useConfig['class'];
567 // @phan-suppress-next-line PhanInvalidFQSENInClasslike
568 $backend = new $class( $useConfig );
569 } else {
570 # Replace with a mock. We do not care about generating real
571 # files on the filesystem, just need to expose the file
572 # informations.
573 $backend = new MockFileBackend( [
574 'name' => 'local-backend',
575 'wikiId' => WikiMap::getCurrentWikiId()
576 ] );
577 }
578
579 $services = MediaWikiServices::getInstance();
580 return new RepoGroup(
581 [
582 'class' => MockLocalRepo::class,
583 'name' => 'local',
584 'url' => 'http://example.com/images',
585 'hashLevels' => 2,
586 'transformVia404' => false,
587 'backend' => $backend
588 ],
589 [],
590 $services->getMainWANObjectCache(),
591 $services->getMimeAnalyzer()
592 );
593 }
594
595 /**
596 * Execute an array in which elements with integer keys are taken to be
597 * callable objects, and other elements are taken to be global variable
598 * set operations, with the key giving the variable name and the value
599 * giving the new global variable value. A closure is returned which, when
600 * executed, sets the global variables back to the values they had before
601 * this function was called.
602 *
603 * @see staticSetup
604 *
605 * @param array $setup
606 * @return closure
607 */
608 protected function executeSetupSnippets( $setup ) {
609 $saved = [];
610 foreach ( $setup as $name => $value ) {
611 if ( is_int( $name ) ) {
612 $value();
613 } else {
614 $saved[$name] = $GLOBALS[$name] ?? null;
615 $GLOBALS[$name] = $value;
616 }
617 }
618 return function () use ( $saved ) {
619 $this->executeSetupSnippets( $saved );
620 };
621 }
622
623 /**
624 * Take a setup array in the same format as the one given to
625 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
626 * executes the snippets in the setup array in reverse order. This is used
627 * to create "teardown objects" for the public API.
628 *
629 * @see staticSetup
630 *
631 * @param array $teardown The snippet array
632 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
633 * @return ScopedCallback
634 */
635 protected function createTeardownObject(
636 array $teardown, ?ScopedCallback $nextTeardown = null
637 ) {
638 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
639 // Schedule teardown snippets in reverse order
640 $teardown = array_reverse( $teardown );
641
642 $this->executeSetupSnippets( $teardown );
643 if ( $nextTeardown ) {
644 ScopedCallback::consume( $nextTeardown );
645 }
646 } );
647 }
648
649 protected function registerHook( string $name, callable $handler ) {
650 $hookContainer = MediaWikiServices::getInstance()->getHookContainer();
651 $reset = $hookContainer->scopedRegister( $name, $handler );
652 return static function () use ( &$reset ) {
653 ScopedCallback::consume( $reset );
654 };
655 }
656
657 /**
658 * Set a setupDone flag to indicate that setup has been done, and return
659 * the teardown closure. If the flag was already set, throw an exception.
660 *
661 * @param string $funcName The setup function name
662 * @return closure
663 */
664 protected function markSetupDone( $funcName ) {
665 if ( $this->setupDone[$funcName] ) {
666 throw new RuntimeException( "$funcName is already done" );
667 }
668 $this->setupDone[$funcName] = true;
669 return function () use ( $funcName ) {
670 $this->setupDone[$funcName] = false;
671 };
672 }
673
674 /**
675 * Ensure one of the given setup stages has been done, throw an exception otherwise.
676 * @param string $funcName
677 */
678 protected function checkSetupDone( string $funcName ) {
679 if ( !$this->setupDone[$funcName] ) {
680 throw new BadMethodCallException( "$funcName must be called before calling " . wfGetCaller() );
681 }
682 }
683
684 /**
685 * Determine whether a particular setup function has been run
686 *
687 * @param string $funcName
688 * @return bool
689 */
690 public function isSetupDone( $funcName ) {
691 return $this->setupDone[$funcName] ?? false;
692 }
693
694 /**
695 * Insert hardcoded interwiki in the lookup table.
696 *
697 * This function insert a set of well known interwikis that are used in
698 * the parser tests. We use the $wgInterwikiCache mechanism to completely
699 * replace any other lookup. (Note that the InterwikiLoadPrefix hook
700 * isn't used because it doesn't alter the result of
701 * Interwiki::getAllPrefixes() and so is incompatible with some users,
702 * including Parsoid.)
703 * @param array &$setup
704 * @param array &$teardown
705 */
706 private function appendInterwikiSetup( &$setup, &$teardown ) {
707 static $testInterwikis = [
708 [
709 'iw_prefix' => 'local',
710 // This is a "local interwiki" (see wgLocalInterwikis elsewhere in this file)
711 'iw_url' => 'http://example.org/wiki/$1',
712 'iw_local' => 1,
713 ],
714 // Local interwiki that matches a namespace name (T228616)
715 [
716 'iw_prefix' => 'project',
717 // This is a "local interwiki" (see wgLocalInterwikis elsewhere in this file)
718 'iw_url' => 'http://example.org/wiki/$1',
719 'iw_local' => 1,
720 ],
721 [
722 'iw_prefix' => 'wikipedia',
723 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
724 'iw_local' => 0,
725 ],
726 [
727 'iw_prefix' => 'meatball',
728 // this has been updated in the live wikis, but the parser tests
729 // expect the old value
730 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
731 'iw_local' => 0,
732 ],
733 [
734 'iw_prefix' => 'memoryalpha',
735 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
736 'iw_local' => 0,
737 ],
738 [
739 'iw_prefix' => 'zh',
740 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
741 'iw_local' => 1,
742 ],
743 [
744 'iw_prefix' => 'es',
745 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
746 'iw_local' => 1,
747 ],
748 [
749 'iw_prefix' => 'fr',
750 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
751 'iw_local' => 1,
752 ],
753 [
754 'iw_prefix' => 'ru',
755 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
756 'iw_local' => 1,
757 ],
758 [
759 'iw_prefix' => 'mi',
760 // This is a "local interwiki" (see wgLocalInterwikis elsewhere in this file)
761 'iw_url' => 'http://example.org/wiki/$1',
762 'iw_local' => 1,
763 ],
764 [
765 'iw_prefix' => 'mul',
766 'iw_url' => 'http://wikisource.org/wiki/$1',
767 'iw_local' => 1,
768 ],
769 // Additions from Parsoid
770 [
771 'iw_prefix' => 'en',
772 'iw_url' => '//en.wikipedia.org/wiki/$1',
773 'iw_local' => 1
774 ],
775 [
776 'iw_prefix' => 'stats',
777 'iw_url' => 'https://stats.wikimedia.org/$1',
778 'iw_local' => 1,
779 ],
780 [
781 'iw_prefix' => 'gerrit',
782 'iw_url' => 'https://gerrit.wikimedia.org/$1',
783 'iw_local' => 1,
784 ],
785 // Added to support T145590#8608455
786 [
787 'iw_prefix' => 'pmid',
788 'iw_url' => '//www.ncbi.nlm.nih.gov/pubmed/$1?dopt=Abstract',
789 'iw_local' => 1,
790 ],
791 // Deliberately missing a $1 in the URL to exercise a common
792 // misconfiguration.
793 [
794 'iw_prefix' => 'wikinvest',
795 'iw_url' => 'https://meta.wikimedia.org/wiki/Interwiki_map/discontinued#Wikinvest',
796 'iw_local' => 1,
797 ],
798 ];
799 // When running from parserTests.php, database setup happens *after*
800 // interwiki setup, and that changes the wiki id. In order to avoid
801 // breaking the interwiki cache, use 'global scope' for the interwiki
802 // lookup.
803 $GLOBAL_SCOPE = 2; // See docs for $wgInterwikiScopes
804 $setup['wgInterwikiScopes'] = $GLOBAL_SCOPE;
805 $setup['wgInterwikiCache'] =
806 ClassicInterwikiLookup::buildCdbHash( $testInterwikis, $GLOBAL_SCOPE );
807 $reset = static function () {
808 // Reset the service in case any other tests already cached some prefixes.
809 MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
810 };
811 $setup[] = $reset;
812 $teardown[] = $reset;
813
814 // This affects title normalization in links. It invalidates
815 // MediaWikiTitleCodec objects.
816 // These interwikis should have 'iw_url' that matches wgServer.
817 $setup['wgLocalInterwikis'] = [ 'local', 'project', 'mi' ];
818 $reset = function () {
819 $this->resetTitleServices();
820 };
821 $setup[] = $reset;
822 $teardown[] = $reset;
823 }
824
825 /**
826 * Reset the Title-related services that need resetting
827 * for each test
828 *
829 * @todo We need to reset all services on every test
830 */
831 private function resetTitleServices() {
832 $services = MediaWikiServices::getInstance();
833 $services->resetServiceForTesting( 'TitleFormatter' );
834 $services->resetServiceForTesting( 'TitleParser' );
835 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
836 $services->resetServiceForTesting( 'LinkRenderer' );
837 $services->resetServiceForTesting( 'LinkRendererFactory' );
838 $services->resetServiceForTesting( 'NamespaceInfo' );
839 $services->resetServiceForTesting( 'SpecialPageFactory' );
840 }
841
842 /**
843 * Remove last character if it is a newline
844 * @param string $s
845 * @return string
846 */
847 public static function chomp( $s ) {
848 if ( str_ends_with( $s, "\n" ) ) {
849 return substr( $s, 0, -1 );
850 } else {
851 return $s;
852 }
853 }
854
855 private function skipAllTestsInFile(
856 string $filename, TestFileReader $testFileInfo, ParserTestMode $mode, string $skipMessage
857 ): void {
858 foreach ( $testFileInfo->testCases as $test ) {
859 $this->recorder->startTest( $test, $mode );
860 $this->recorder->skipped( $test, $mode, $skipMessage );
861 }
862 $this->recorder->endSuite( $filename );
863 }
864
865 /**
866 * Run a series of tests listed in the given text files.
867 * Each test consists of a brief description, wikitext input,
868 * and the expected HTML output.
869 *
870 * Prints status updates on stdout and counts up the total
871 * number and percentage of passed tests.
872 *
873 * Handles all setup and teardown.
874 *
875 * @param string[] $filenames
876 * @return bool True if passed all tests, false if any tests failed.
877 */
878 public function runTestsFromFiles( $filenames ) {
879 $ok = false;
880
881 $teardownGuard = null;
882 $teardownGuard = $this->setupDatabase( $teardownGuard );
883 $teardownGuard = $this->staticSetup( $teardownGuard );
884 $teardownGuard = $this->setupUploads( $teardownGuard );
885
886 $this->recorder->start();
887 try {
888 $ok = true;
889 $inParsoidMode = $this->options['parsoid'];
890 if ( $inParsoidMode ) {
891 $legacyMode = null;
892 $skipMode = new ParserTestMode( 'parsoid' );
893 } else {
894 $legacyMode = $skipMode = new ParserTestMode( 'legacy' );
895 }
896
897 foreach ( $filenames as $filename ) {
898 $this->recorder->startSuite( $filename );
899
900 $testFileInfo = TestFileReader::read( $filename,
901 static function ( $msg ) {
902 wfDeprecatedMsg( $msg, '1.35', false, false );
903 }
904 );
905
906 $skipMessage = $this->getFileSkipMessage( !$inParsoidMode, $testFileInfo->fileOptions, $filename );
907 if ( $skipMessage !== null ) {
908 $this->skipAllTestsInFile( $filename, $testFileInfo, $skipMode, $skipMessage );
909 continue;
910 }
911
912 $parsoidTestModeStrs = [];
913 if ( $inParsoidMode ) { // Intersect requested modes with test modes enabled in the file
914 $parsoidTestModeStrs = $this->computeValidTestModes(
915 $this->getRequestedTestModes(), $testFileInfo->fileOptions );
916
917 if ( !$parsoidTestModeStrs ) {
918 $skipMessage = 'No compatible Parsoid modes found for the file';
919 $this->skipAllTestsInFile( $filename, $testFileInfo, $skipMode, $skipMessage );
920 continue;
921 }
922 }
923
924 $this->checkSetupDone( 'staticSetup' );
925 $teardown = $this->addArticles( $testFileInfo->articles );
926
927 // Run tests
928 foreach ( $testFileInfo->testCases as $test ) {
929 $skipMessage = $this->getTestSkipMessage( $test, !$inParsoidMode );
930 if ( $skipMessage !== null ) {
931 if ( $skipMessage !== self::FILTER_MSG ) {
932 $this->recorder->startTest( $test, $skipMode );
933 $this->recorder->skipped( $test, $skipMode, $skipMessage );
934 }
935 continue;
936 }
937
938 if ( $inParsoidMode ) {
939 // calls runTestInternal for each mode
940 $passed = $this->runTestInParsoidModes( $test, $parsoidTestModeStrs );
941 } else {
942 '@phan-var ParserTestMode $legacyMode'; // assert that this is not null
943 $passed = $this->runTestInternal( $test, $legacyMode )->isSuccess();
944 }
945
946 $ok = $ok && $passed;
947 }
948
949 // Update tests / known-failures
950 if ( $inParsoidMode && $this->options['updateKnownFailures'] ) {
951 $this->updateKnownFailures( $filename, $testFileInfo );
952 }
953
954 if ( $this->options['update-tests'] ) {
955 $this->updateTests( $filename, $testFileInfo, !$inParsoidMode );
956 }
957
958 // Clean up
959 ScopedCallback::consume( $teardown );
960
961 $this->recorder->endSuite( $filename );
962 }
963
964 $this->recorder->report();
965 } catch ( DBError $e ) {
966 $this->recorder->warning( $e->getMessage() );
967 }
968 $this->recorder->end();
969
970 ScopedCallback::consume( $teardownGuard );
971
972 return $ok;
973 }
974
975 /**
976 * Determine whether the current parser has the hooks registered in it
977 * that are required by a file read by TestFileReader.
978 * @param array[] $requirements
979 * @return bool
980 */
981 public function meetsRequirements( $requirements ) {
982 foreach ( $requirements as $requirement ) {
983 $ok = true;
984 switch ( $requirement['type'] ) {
985 case 'hook':
986 $ok = $this->requireHook( $requirement['name'] );
987 break;
988 case 'functionHook':
989 $ok = $this->requireFunctionHook( $requirement['name'] );
990 break;
991 }
992 if ( !$ok ) {
993 return false;
994 }
995 }
996 return true;
997 }
998
999 /**
1000 * @param bool $isLegacy
1001 * @param array $fileOptions
1002 * @param string $filename
1003 * @return string|null
1004 */
1005 public function getFileSkipMessage( bool $isLegacy, array $fileOptions, string $filename ): ?string {
1006 $runnerOpts = $this->getOptions();
1007 // Verify minimum version #
1008 $testFormat = intval( $fileOptions['version'] ?? '1' );
1009 if ( $testFormat < 2 ) {
1010 throw new RuntimeException(
1011 "$filename needs an update. Support for the parserTest v1 file format was removed in MediaWiki 1.36"
1012 );
1013 }
1014
1015 // If any requirements are not met, mark all tests from the file as skipped
1016 if ( !(
1017 $isLegacy ||
1018 isset( $fileOptions['parsoid-compatible'] )
1019 ) ) {
1020 // Running files in Parsoid integrated mode is opt-in for now.
1021 return 'not compatible with Parsoid integrated mode';
1022 } elseif ( !$this->meetsRequirements( $fileOptions['requirements'] ?? [] ) ) {
1023 return 'required extension not enabled';
1024 } elseif ( ( $runnerOpts['testFile'] ?? $filename ) !== $filename ) {
1025 return 'Not the requested test file';
1026 } else {
1027 return null;
1028 }
1029 }
1030
1031 public function getTestSkipMessage( ParserTest $test, bool $isLegacy ): ?string {
1032 $opts = $test->options;
1033
1034 if ( !$test->matchesFilter( [ 'regex' => $this->regex ] ) ) {
1035 return self::FILTER_MSG;
1036 }
1037
1038 // Skip deprecated preprocessor tests
1039 if ( isset( $opts['preprocessor'] ) && $opts['preprocessor'] !== 'Preprocessor_Hash' ) {
1040 wfDeprecated( 'preprocessor=Preprocessor_DOM', '1.36' );
1041 return "Unsupported preprocessor type";
1042 }
1043 if ( $test->wikitext === null ) {
1044 // Note that /in theory/ we could have pure html2html tests
1045 // with no wikitext section, but /in practice/ all tests
1046 // include a wikitext section.
1047 $test->error( "Test lacks wikitext section", $test->testName );
1048 }
1049 // Skip disabled / filtered tests
1050 if ( isset( $opts['disabled'] ) && !$this->runDisabled ) {
1051 return "Test disabled";
1052 }
1053
1054 // Skip parsoid-only tests if running in a legacy test mode
1055 if (
1056 $test->legacyHtml === null &&
1057 self::getLegacyMetadataSection( $test ) === null
1058 ) {
1059 // A Parsoid-only test should have one of the following sections
1060 if (
1061 isset( $test->sections['html/parsoid'] ) ||
1062 isset( $test->sections['html/parsoid+integrated'] ) ||
1063 isset( $test->sections['html/parsoid+standalone'] ) ||
1064 isset( $test->sections['wikitext/edited'] ) ||
1065 self::getParsoidMetadataSection( $test ) !== null
1066 ) {
1067 if ( $isLegacy ) {
1068 // Not an error, just skip this test if we're in
1069 // legacy mode.
1070 return "Parsoid-only test";
1071 }
1072 } else {
1073 // This test lacks both a legacy html or metadata
1074 // section and also any parsoid-specific html or
1075 // metadata section or wikitext/edited section.
1076 $test->error( "Test lacks html or metadata section", $test->testName );
1077 }
1078 }
1079 return null;
1080 }
1081
1082 public static function getLegacyMetadataSection( ParserTest $test ) {
1083 return // specific results for legacy parser
1084 $test->sections['metadata/php'] ??
1085 // specific results for legacy parser and parsoid integrated mode
1086 $test->sections['metadata/integrated'] ??
1087 // generic for all parsers (even standalone)
1088 $test->sections['metadata'] ??
1089 // missing (== use legacy combined output format)
1090 null;
1091 }
1092
1093 public static function getParsoidMetadataSection( ParserTest $test ) {
1094 return // specific results for parsoid integrated mode
1095 $test->sections['metadata/parsoid+integrated'] ??
1096 // specific results for parsoid
1097 $test->sections['metadata/parsoid'] ??
1098 // specific results for legacy parser and parsoid integrated mode
1099 $test->sections['metadata/integrated'] ??
1100 // generic for all parsers (even standalone)
1101 $test->sections['metadata'] ??
1102 // missing (== use legacy combined output format)
1103 null;
1104 }
1105
1106 /**
1107 * Compute valid test modes based on requested modes and file-enabled modes
1108 * @param string[] $testModes
1109 * @param array $fileOptions
1110 * @return string[]
1111 */
1112 public function computeValidTestModes( array $testModes, array $fileOptions ): array {
1113 $modeRestriction = $fileOptions['parsoid-compatible'] ?: false;
1114 if ( $modeRestriction !== false ) {
1115 if ( is_string( $modeRestriction ) ) {
1116 // shorthand
1117 $modeRestriction = [ $modeRestriction ];
1118 }
1119 $testModes = array_values( array_intersect( $testModes, $modeRestriction ) );
1120 }
1121
1122 return $testModes;
1123 }
1124
1125 /**
1126 * Run the tests from a single file. staticSetup() and setupDatabase()
1127 * must have been called already.
1128 *
1129 * @param ParserTest $t
1130 * @param string[] $testModeStrs What Parsoid modes to run these these in?
1131 * @return bool True if passed all modes, false if any mode failed.
1132 */
1133 private function runTestInParsoidModes( ParserTest $t, array $testModeStrs ): bool {
1134 if ( $this->options['updateKnownFailures'] ) {
1135 // Reset known failures to ensure we reset newly skipped tests
1136 $t->knownFailures = [];
1137 }
1138
1139 $ok = true;
1140 $runner = $this;
1141 $t->testAllModes( $t->computeTestModes( $testModeStrs ), $this->options,
1142 function ( ParserTest $test, string $modeStr, array $options ) use ( $runner, $t, &$ok ) {
1143 // $test could be a clone of $t
1144 // Ensure that updates to knownFailures in $test are reflected in $t
1145 $test->knownFailures = &$t->knownFailures;
1146 $mode = new ParserTestMode( $modeStr, $test->changetree );
1147 if ( $modeStr === 'selser' && $test->changetree === null ) {
1148 // This is an auto-edit test with either a CLI changetree
1149 // or a change tree that should be generated
1150 $changetree = $runner->options['changetree'] ? json_decode( $runner->options['changetree'] ) : null;
1151 $mode = new ParserTestMode( 'selser-auto', $changetree );
1152 }
1153 $result = $this->runTestInternal( $test, $mode );
1154 $ok = $ok && $result->isSuccess();
1155 }
1156 );
1157
1158 return $ok;
1159 }
1160
1161 /**
1162 * Update known failures JSON file for the parser tests file
1163 * @param string $filename The parser test file
1164 * @param TestFileReader $testFileInfo
1165 */
1166 public function updateKnownFailures( string $filename, TestFileReader $testFileInfo ) {
1167 $testKnownFailures = [];
1168 foreach ( $testFileInfo->testCases as $t ) {
1169 if ( $t->knownFailures && $t->testName ) {
1170 // @phan-suppress-next-line PhanTypeMismatchDimAssignment False positive
1171 $testKnownFailures[$t->testName] = $t->knownFailures;
1172 // FIXME: This reduces noise when updateKnownFailures is used
1173 // with a subset of test modes. But, this also mixes up the selser
1174 // test results with non-selser ones.
1175 // ksort( $testKnownFailures[$t->testName] );
1176 }
1177 }
1178 // Sort, otherwise, titles get added above based on the first
1179 // failing mode, which can make diffs harder to verify when
1180 // failing modes change.
1181 ksort( $testKnownFailures );
1182 // Cast to object to ensure that empty list is encoded as `{}` not `[]`
1183 $contents = FormatJson::encode( (object)$testKnownFailures, "\t", FormatJson::ALL_OK ) . "\n";
1184
1185 if ( file_exists( $testFileInfo->knownFailuresPath ) ) {
1186 $old = file_get_contents( $testFileInfo->knownFailuresPath );
1187 } else {
1188 // If file doesn't exist, use the JSON representation of an
1189 // empty array, so it compares equal in the case that we
1190 // end up with an empty array of known failures below.
1191 $old = "{}";
1192 }
1193
1194 if ( $old !== $contents ) {
1195 if ( $testFileInfo->knownFailuresPath ) {
1196 $this->recorder->warning( "Updating known failures file: {$testFileInfo->knownFailuresPath}" );
1197 file_put_contents( $testFileInfo->knownFailuresPath, $contents );
1198 } else {
1199 // To be safe, we don't try to write a file that doesn't
1200 // (yet) exist. Create an empty file if you need to, and
1201 // then we'll happily update it for you.
1202 throw new RuntimeException(
1203 "Known failures file for $filename does not exist, " .
1204 "and so won't be updated."
1205 );
1206 }
1207 }
1208 }
1209
1210 /**
1211 * @param string $filename The parser test file
1212 * @param TestFileReader $testFileInfo
1213 * @param bool $isLegacy
1214 */
1215 public function updateTests(
1216 string $filename, TestFileReader $testFileInfo, bool $isLegacy
1217 ) {
1218 $fileContent = file_get_contents( $filename );
1219 foreach ( $testFileInfo->testCases as $t ) {
1220 $testName = $t->testName;
1221 $fail = $t->knownFailures[$isLegacy ? 'legacy' : 'wt2html'] ?? null;
1222 $html = $isLegacy ? $t->legacyHtml : $t->parsoidHtml;
1223 if ( $isLegacy && $fail === null ) {
1224 $fail = $t->knownFailures['metadata'] ?? null;
1225 $html = self::getLegacyMetadataSection( $t );
1226 }
1227 if ( $testName !== null && $fail !== null && $html !== null ) {
1228 $exp = '/(!!\s*test\s*' .
1229 preg_quote( $testName, '/' ) .
1230 '(?:(?!!!\s*end)[\s\S])*' .
1231 ')(' . preg_quote( $html, '/' ) .
1232 ')/m';
1233 $fileContent = preg_replace_callback(
1234 $exp,
1235 static function ( array $matches ) use ( $fail ) {
1236 return $matches[1] . $fail;
1237 },
1238 $fileContent
1239 );
1240 }
1241 }
1242 file_put_contents( $filename, $fileContent );
1243 }
1244
1245 /**
1246 * @param string $wikitext
1247 * @return array
1248 */
1249 private function getRevRecordProperties( string $wikitext ): array {
1250 return [
1251 'pageid' => 187, // Some random fake page id
1252 'revid' => 1337, // see Parser::getRevisionId()
1253 'timestamp' => $this->getFakeTimestamp(),
1254 'wikitext' => $wikitext
1255 ];
1256 }
1257
1258 /**
1259 * Create a mutable rev record for test use.
1260 *
1261 * @param LinkTarget $target
1262 * @param UserIdentity $user
1263 * @param array $revProps
1264 * @return RevisionRecord
1265 */
1266 private function createRevRecord( LinkTarget $target, UserIdentity $user, array $revProps ): RevisionRecord {
1267 $content = new WikitextContent( $revProps['wikitext'] );
1268 $title = MediaWikiServices::getInstance()->getTitleFactory()->newFromRow( (object)[
1269 'page_id' => $revProps['pageid'],
1270 'page_len' => $content->getSize(),
1271 'page_latest' => $revProps['revid'],
1272 'page_namespace' => $target->getNamespace(),
1273 'page_title' => $target->getDBkey(),
1274 'page_is_redirect' => 0
1275 ] );
1276
1277 $revRecord = new MutableRevisionRecord( $title );
1278 $revRecord->setContent( SlotRecord::MAIN, $content )
1279 ->setUser( $user )
1280 ->setTimestamp( strval( $revProps['timestamp'] ) )
1281 ->setPageId( $title->getArticleID() )
1282 ->setId( $title->getLatestRevID() );
1283
1284 return $revRecord;
1285 }
1286
1287 /**
1288 * Shared code to initialize ParserOptions based on the $test object,
1289 * used by both the legacy Parser and the Parsoid parser.
1290 * @param ParserTest $test
1291 * @param callable(IContextSource,LinkTarget,array):ParserOptions $parserOptionsCallback A callback to create the
1292 * initial ParserOptions object. This allows for some minor
1293 * differences in how the legacy Parser and Parsoid create this.
1294 * @return array<LinkTarget|ParserOptions|int> An array of LinkTarget, ParserOptions, and integer revId.
1295 * @phan-return array{0:LinkTarget,1:ParserOptions,2:int}
1296 */
1297 private function setupParserOptions( ParserTest $test, callable $parserOptionsCallback ) {
1298 $opts = $test->options;
1299 $context = RequestContext::getMain();
1300 $wikitext = $test->wikitext;
1301 '@phan-var string $wikitext'; // assert that this is not null
1302 $revProps = $this->getRevRecordProperties( $wikitext );
1303 $user = $context->getUser();
1304 $title = isset( $opts['title'] )
1305 ? MediaWikiServices::getInstance()->getTitleParser()->parseTitle( $opts['title'] )
1306 : new TitleValue( NS_MAIN, 'Parser test' );
1307
1308 $revRecord = null;
1309 if ( isset( $opts['lastsavedrevision'] ) ) {
1310 $revRecord = $this->createRevRecord( $title, $user, $revProps );
1311 $revProps['rev'] = $revRecord;
1312 // Increment timestamp so that parser tests can distinguish between
1313 // ParserOptions source and RevisionRecord
1314 $revProps['timestamp'] += 234;
1315 }
1316
1317 $options = $parserOptionsCallback( $context, $title, $revProps );
1318 $options->setTimestamp(
1319 MWTimestamp::convert( TS_MW, $revProps['timestamp'] )
1320 );
1321 $options->setUserLang( $opts['userlanguage'] ?? $context->getLanguage() );
1322
1323 if ( isset( $opts['lastsavedrevision'] ) ) {
1324 $oldCallback = $options->getCurrentRevisionRecordCallback();
1325 $options->setCurrentRevisionRecordCallback(
1326 static function ( LinkTarget $link, $parser = null ) use ( $title, $revRecord, $oldCallback ) {
1327 if ( $link->isSameLinkAs( $title ) ) {
1328 return $revRecord;
1329 } else {
1330 return $oldCallback( $link, $parser );
1331 }
1332 }
1333 );
1334 }
1335
1336 if ( isset( $opts['maxincludesize'] ) ) {
1337 $options->setMaxIncludeSize( $opts['maxincludesize'] );
1338 }
1339 if ( isset( $opts['maxtemplatedepth'] ) ) {
1340 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
1341 }
1342
1343 return [ $title, $options, $revProps['revid'] ];
1344 }
1345
1346 /**
1347 * Get a Parser object
1348 *
1349 * @return Parser
1350 */
1351 public function getParser() {
1352 $parserFactory = MediaWikiServices::getInstance()->getParserFactory();
1353 $parser = $parserFactory->create(); // A fresh parser object.
1354 ParserTestParserHook::setup( $parser );
1355 return $parser;
1356 }
1357
1358 /**
1359 * Run a given wikitext input through either the legacy wiki parser
1360 * or Parsoid, depending on the given test mode, and compare the
1361 * output against the expected results.
1362 *
1363 * @param ParserTest $test The test parameters
1364 * @param ParserTestMode $mode The test mode
1365 * @return ParserTestResult The test results.
1366 */
1367 private function runTestInternal( ParserTest $test, ParserTestMode $mode ): ParserTestResult {
1368 $this->recorder->startTest( $test, $mode );
1369 if ( $mode->isLegacy() ) {
1370 $result = $this->runLegacyTest( $test, $mode );
1371 } else {
1372 // Parsoid might skip a test for unsupported features
1373 $result = $this->runParsoidTest( $test, $mode );
1374 if ( $result === false ) {
1375 $this->recorder->skipped( $test, $mode, 'SKIP' );
1376 return new ParserTestResult( $test, $mode, 'SKIP', 'SKIP' );
1377 }
1378 }
1379 $this->recorder->record( $result );
1380 return $result;
1381 }
1382
1383 /**
1384 * Run a given wikitext input through either the legacy wiki parser
1385 * or Parsoid, depending on the given test mode, and compare the
1386 * output against the expected results.
1387 *
1388 * @param ParserTest $test The test parameters
1389 * @param ParserTestMode $mode The test mode
1390 * @return ParserTestResult The test results.
1391 */
1392 public function runTest( ParserTest $test, ParserTestMode $mode ): ParserTestResult {
1393 $skipMessage = $this->getTestSkipMessage( $test, $mode->isLegacy() );
1394 if ( $skipMessage !== null ) {
1395 if ( $skipMessage !== self::FILTER_MSG ) {
1396 $this->recorder->startTest( $test, $mode );
1397 $this->recorder->skipped( $test, $mode, $skipMessage );
1398 }
1399 return new ParserTestResult( $test, $mode, 'SKIP', 'SKIP' );
1400 }
1401 return $this->runTestInternal( $test, $mode );
1402 }
1403
1404 /**
1405 * Run a given wikitext input through a freshly-constructed instance
1406 * of the legacy wiki parser, and compare the output against the expected
1407 * results.
1408 *
1409 * Prints status and explanatory messages to stdout.
1410 *
1411 * staticSetup() and setupWikiData() must be called before this function
1412 * is entered.
1413 *
1414 * @param ParserTest $test The test parameters
1415 * @param ParserTestMode $mode The test mode
1416 * @return ParserTestResult
1417 */
1418 public function runLegacyTest( ParserTest $test, ParserTestMode $mode ): ParserTestResult {
1419 $desc = ( $test->comment ?? '' ) . $test->testName;
1420 wfDebug( __METHOD__ . ": running $desc" );
1421 $teardownGuard = $this->perTestSetup( $test );
1422 [ $title, $options, $revId ] = $this->setupParserOptions(
1423 $test,
1424 static function ( $context, $title, $revProps ) {
1425 return ParserOptions::newFromContext( $context );
1426 }
1427 );
1428
1429 $opts = $test->options;
1430 $local = isset( $opts['local'] );
1431 $parser = $this->getParser();
1432
1433 if ( isset( $opts['styletag'] ) ) {
1434 // For testing the behavior of <style> (including those deduplicated
1435 // into <link> tags), add tag hooks to allow them to be generated.
1436 $parser->setHook( 'style', static function ( $content, $attributes, $parser ) {
1437 $marker = Parser::MARKER_PREFIX . '-style-' . md5( $content ) . Parser::MARKER_SUFFIX;
1438 // @phan-suppress-next-line SecurityCheck-XSS
1439 $parser->getStripState()->addNoWiki( $marker, $content );
1440 return Html::inlineStyle( $marker, 'all', $attributes );
1441 } );
1442 $parser->setHook( 'link', static function ( $content, $attributes, $parser ) {
1443 return Html::element( 'link', $attributes );
1444 } );
1445 }
1446
1447 $wikitext = $test->wikitext;
1448 $output = null;
1449 $pageReference = new PageReferenceValue( $title->getNamespace(), $title->getDBkey(), PageReferenceValue::LOCAL );
1450 '@phan-var string $wikitext'; // assert that this is not null
1451 if ( isset( $opts['pst'] ) ) {
1452 $out = $parser->preSaveTransform( $wikitext, $pageReference, $options->getUserIdentity(), $options );
1453 $output = $parser->getOutput();
1454 } elseif ( isset( $opts['msg'] ) ) {
1455 $out = $parser->transformMsg( $wikitext, $options, $pageReference );
1456 } elseif ( isset( $opts['section'] ) ) {
1457 $section = $opts['section'];
1458 $out = $parser->getSection( $wikitext, $section );
1459 } elseif ( isset( $opts['replace'] ) ) {
1460 $section = $opts['replace'][0];
1461 $replace = $opts['replace'][1];
1462 $out = $parser->replaceSection( $wikitext, $section, $replace );
1463 } elseif ( isset( $opts['comment'] ) ) {
1464 $out = MediaWikiServices::getInstance()->getCommentFormatter()->format( $wikitext, $title, $local );
1465 } elseif ( isset( $opts['preload'] ) ) {
1466 $out = $parser->getPreloadText( $wikitext, $pageReference, $options );
1467 } else {
1468 $output = $parser->parse( $wikitext, $pageReference, $options, true, true, $revId );
1469 if ( isset( $opts['nohtml'] ) ) {
1470 $out = '';
1471 } else {
1472 // TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
1473 // This may be a case where it may be reasonable to keep accessing the pipeline directly.
1474 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
1475 $out = $pipeline->run( $output, $options, [
1476 'allowTOC' => !isset( $opts['notoc'] ),
1477 'unwrap' => !isset( $opts['wrap'] ),
1478 'skin' => $this->getSkin( $opts['skin'] ?? 'fallback' ),
1479 ] )->getContentHolderText();
1480 $out = rtrim( $out );
1481 }
1482 }
1483
1484 $metadataExpected = self::getLegacyMetadataSection( $test );
1485 $metadataActual = null;
1486 if ( $output ) {
1487 $this->addParserOutputInfo(
1488 $out, $output, $opts, $title,
1489 $metadataExpected, $metadataActual
1490 );
1491 }
1492
1493 ScopedCallback::consume( $teardownGuard );
1494
1495 $rawOut = $out;
1496 $expected = $test->legacyHtml ?? '';
1497 if ( count( $this->normalizationFunctions ) ) {
1498 $expected = ParserTestResultNormalizer::normalize(
1499 $expected, $this->normalizationFunctions );
1500 $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
1501 }
1502
1503 $testResult = new ParserTestResult( $test, $mode, $expected, $out );
1504
1505 if ( $this->options['update-tests'] && !$testResult->isSuccess() ) {
1506 $test->knownFailures["$mode"] = $rawOut;
1507 }
1508
1509 if ( $testResult->isSuccess() && $metadataExpected !== null ) {
1510 $testResult = new ParserTestResult( $test, $mode, $metadataExpected, $metadataActual ?? '' );
1511
1512 if ( $this->options['update-tests'] && !$testResult->isSuccess() ) {
1513 $test->knownFailures['metadata'] = $metadataActual;
1514 }
1515 }
1516
1517 return $testResult;
1518 }
1519
1520 private function getSkin( $name ) {
1521 static $skinCache = [];
1522
1523 $skinCache[$name] ??= MediaWikiServices::getInstance()->getSkinFactory()->makeSkin( $name );
1524 return $skinCache[$name];
1525 }
1526
1527 /**
1528 * Add information from the parser output to the result string
1529 *
1530 * @param string &$out The "actual" parser output
1531 * @param ParserOutput $output The "actual" parser metadata
1532 * @param array $opts Test options
1533 * @param ParsoidLinkTarget $title
1534 * @param ?string $metadataExpected The contents of the !!metadata section,
1535 * or null if it is missing
1536 * @param ?string &$metadataActual The "actual" metadata output
1537 */
1538 private function addParserOutputInfo(
1539 &$out, ParserOutput $output, array $opts, ParsoidLinkTarget $title,
1540 ?string $metadataExpected, ?string &$metadataActual
1541 ) {
1542 $before = [];
1543 $after = [];
1544 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
1545 // The "before" entries may contain HTML.
1546 if ( isset( $opts['showtitle'] ) ) {
1547 if ( $output->getTitleText() ) {
1548 $titleText = $output->getTitleText();
1549 } else {
1550 // TitleFormatter doesn't (yet) take ParsoidLinkTarget
1551 // (which is identical to core's LinkTarget, but phan doesn't
1552 // know that), so go through TitleValue for now.
1553 $titleText = $titleFormatter->getPrefixedText(
1554 TitleValue::newFromLinkTarget( $title )
1555 );
1556 }
1557 $before[] = $titleText;
1558 }
1559
1560 if ( isset( $opts['showindicators'] ) ) {
1561 foreach ( $output->getIndicators() as $id => $content ) {
1562 $before[] = "$id=$content";
1563 }
1564 }
1565
1566 if ( isset( $opts['cat'] ) ) {
1567 $defaultSortKey = $output->getPageProperty( 'defaultsort' ) ?? '';
1568 foreach ( $output->getCategoryNames() as $name ) {
1569 $sortkey = $output->getCategorySortKey( $name ) ?: $defaultSortKey;
1570 $after[] = "cat=$name sort=$sortkey";
1571 }
1572 }
1573
1574 if ( isset( $opts['extlinks'] ) ) {
1575 foreach ( $output->getExternalLinks() as $url => $ignore ) {
1576 $after[] = "extlink=$url";
1577 }
1578 }
1579
1580 if ( isset( $opts['ill'] ) ) {
1581 foreach ( $output->getLanguageLinks() as $ll ) {
1582 $after[] = "ill=$ll";
1583 }
1584 }
1585
1586 if ( isset( $opts['iwl'] ) ) {
1587 foreach ( $output->getInterwikiLinks() as $prefix => $arr ) {
1588 foreach ( $arr as $dbk => $ignore ) {
1589 $after[] = "iwl=$prefix:$dbk";
1590 }
1591 }
1592 }
1593
1594 if ( isset( $opts['links'] ) ) {
1595 foreach ( $output->getLinks() as $ns => $arr ) {
1596 foreach ( $arr as $dbk => $page_id ) {
1597 $nsName = $titleFormatter->getNamespaceName( $ns, $dbk );
1598 $t = $nsName ? "$nsName:$dbk" : $dbk;
1599 $after[] = "link=$t";
1600 }
1601 }
1602 }
1603
1604 if ( isset( $opts['special'] ) ) {
1605 foreach ( $output->getLinksSpecial() as $dbk => $ignore ) {
1606 $after[] = "special=Special:$dbk";
1607 }
1608 }
1609
1610 if ( isset( $opts['templates'] ) ) {
1611 foreach ( $output->getTemplates() as $ns => $arr ) {
1612 foreach ( $arr as $dbk => $page_id ) {
1613 $nsName = $titleFormatter->getNamespaceName( $ns, $dbk );
1614 $t = $nsName ? "$nsName:$dbk" : $dbk;
1615 $after[] = "template=$t";
1616 }
1617 }
1618 }
1619
1620 if ( isset( $opts['extension'] ) ) {
1621 $extList = $opts['extension'];
1622 if ( !is_array( $extList ) ) {
1623 $extList = [ $extList ];
1624 }
1625 foreach ( $extList as $ext ) {
1626 $after[] = "extension[$ext]=" .
1627 // XXX should use JsonCodec
1628 json_encode(
1629 $output->getExtensionData( $ext ),
1630 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT
1631 );
1632 }
1633 }
1634
1635 if ( isset( $opts['property'] ) ) {
1636 $propList = $opts['property'];
1637 if ( !is_array( $propList ) ) {
1638 $propList = [ $propList ];
1639 }
1640 foreach ( $propList as $prop ) {
1641 $after[] = "property[$prop]=" .
1642 ( $output->getPageProperty( $prop ) ?? '' );
1643 }
1644 }
1645 if ( isset( $opts['showflags'] ) ) {
1646 $actualFlags = [];
1647 foreach ( ParserOutputFlags::cases() as $name ) {
1648 if ( $output->getOutputFlag( $name ) ) {
1649 $actualFlags[] = $name;
1650 }
1651 }
1652 sort( $actualFlags );
1653 $after[] = "flags=" . implode( ', ', $actualFlags );
1654 # In 1.21 we deprecated the use of arbitrary keys for
1655 # ParserOutput::setFlag() by extensions; if we find anyone
1656 # still doing that complain about it.
1657 $oldFlags = array_diff_key(
1658 TestingAccessWrapper::newFromObject( $output )->mFlags,
1659 array_fill_keys( ParserOutputFlags::cases(), true )
1660 );
1661 if ( $oldFlags ) {
1662 wfDeprecated( 'Arbitrary flags in ParserOutput', '1.39' );
1663 }
1664 }
1665 if ( isset( $opts['showtocdata'] ) ) {
1666 $tocData = $output->getTOCData();
1667 if ( $tocData !== null ) {
1668 $after[] = $tocData->prettyPrint();
1669 }
1670 }
1671 if ( isset( $opts['showmedia'] ) ) {
1672 $after[] = 'images=' . implode( ', ', array_keys( $output->getImages() ) );
1673 }
1674 if ( $metadataExpected === null ) {
1675 // legacy format, add $before and $after to $out
1676 if ( $before ) {
1677 $before = implode( "\n", $before );
1678 $out = "$before\n$out";
1679 }
1680 if ( $after ) {
1681 if ( $out && !str_ends_with( $out, "\n" ) ) {
1682 $out .= "\n";
1683 }
1684 $out .= implode( "\n", $after );
1685 }
1686 } else {
1687 $metadataActual = implode( "\n", array_merge( $before, $after ) );
1688 }
1689 }
1690
1691 /**
1692 * This processes test results and updates the known failures info for the test
1693 *
1694 * @param ParserTest $test
1695 * @param ParserTestMode $mode
1696 * @param string|null|callable $rawExpected
1697 * If null, indicates that the normalizer should look for the expected
1698 * output in the $test object.
1699 * @param string $rawActual
1700 * @param callable $normalizer normalizer of expected & actual output strings
1701 * @return ParserTestResult|false
1702 */
1703 private function processResults(
1704 ParserTest $test, ParserTestMode $mode, $rawExpected, string $rawActual, callable $normalizer
1705 ) {
1706 if ( $mode->isCachingMode() ) {
1707 return false;
1708 }
1709
1710 if ( !$this->options['knownFailures'] ) {
1711 $expectedFailure = null;
1712 } else {
1713 $expectedFailure = $test->knownFailures["$mode"] ?? null;
1714 }
1715 if ( $expectedFailure !== null ) {
1716 $expectedFailure = $test->normalizeKnownFailure( $expectedFailure );
1717 }
1718 $rawActualFailure = $test->normalizeKnownFailure( $rawActual );
1719
1720 $expectedToFail = $expectedFailure !== null;
1721 $knownFailureChanged = $expectedToFail && $expectedFailure !== $rawActualFailure;
1722
1723 if ( is_callable( $rawExpected ) ) {
1724 $rawExpected = $rawExpected();
1725 }
1726 [ $actual, $expected ] = $normalizer( $rawActual, $rawExpected, false /* standalone */ );
1727 $passed = $actual === $expected;
1728
1729 $unexpectedPass = $expectedToFail && $passed;
1730 $unexpectedFail = !$expectedToFail && !$passed;
1731
1732 if ( $unexpectedPass ) {
1733 $this->recorder->warning( "{$test->testName}: $mode: EXPECTED TO FAIL, BUT PASSED!" );
1734 } elseif ( $knownFailureChanged ) {
1735 $this->recorder->warning( "{$test->testName}: $mode: UNEXPECTED CHANGE TO KNOWN FAILURE OUTPUT" );
1736 }
1737
1738 if ( $this->options['updateKnownFailures'] && (
1739 $knownFailureChanged || $unexpectedFail || $unexpectedPass
1740 ) ) {
1741 if ( $unexpectedPass ) {
1742 unset( $test->knownFailures["$mode"] );
1743 } else {
1744 $test->knownFailures["$mode"] = $rawActualFailure;
1745 }
1746 }
1747
1748 if ( $this->options['update-tests'] && !$passed ) {
1749 $test->knownFailures["$mode"] = $rawActual;
1750 }
1751
1752 if ( $unexpectedPass ) {
1753 if ( !$this->options['updateKnownFailures'] ) {
1754 $this->unexpectedTestPasses = true;
1755 }
1756 } elseif ( $expectedToFail ) {
1757 '@phan-var string $expectedFailure'; // non-null implied by $expectedToFail
1758 $expected = $expectedFailure;
1759 $actual = $rawActualFailure;
1760 }
1761
1762 return new ParserTestResult( $test, $mode, $expected, $actual );
1763 }
1764
1765 private function fetchCachedDoc( $parsoid, $pageConfig, $test ) {
1766 // If cachedBODYstr is not already set, create it here.
1767 if ( $test->cachedBODYstr === null ) {
1768 $this->wt2html( $parsoid, $pageConfig, $test, new ParserTestMode( 'cache' ) );
1769 }
1770 $doc = DOMUtils::parseHTML( $test->cachedBODYstr, true );
1771 // XXX applyChanges calls functions in WTUtils which assume we
1772 // have a DataBag associated with the document.
1773 DOMDataUtils::prepareDoc( $doc );
1774 return $doc;
1775 }
1776
1777 private function fetchCachedWt( $parsoid, $pageConfig, $test ) {
1778 // If cachedWTstr is not already set, set it here.
1779 if ( ( $test->cachedWTstr ?? null ) === null ) {
1780 $this->html2wt( $parsoid, $pageConfig, $test, new ParserTestMode( 'cache' ) );
1781 }
1782 return $test->cachedWTstr;
1783 }
1784
1785 /**
1786 * Run wt2html on the test
1787 *
1788 * @param Parsoid $parsoid
1789 * @param PageConfig $pageConfig
1790 * @param ParserTest $test
1791 * @param ParserTestMode $mode
1792 * @return ParserTestResult|false false if skipped
1793 */
1794 private function wt2html( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
1795 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
1796 Assert::invariant(
1797 $test->wikitext !== null,
1798 "All tests include a wikitext section"
1799 );
1800
1801 if ( $html === null && !$mode->isCachingMode() && !isset( $test->options['nohtml'] ) ) {
1802 // Nothing to test, but if mode is 'cache' we're executing this
1803 // in order to set cachedBODYstr (say, for a wt2wt test)
1804 // If the 'nohtml' option is set, we're executing this in order
1805 // to test metadata.
1806 return false;
1807 }
1808
1809 $metadata = new ParserOutput( 'parsoid' );
1810 $origOut = $parsoid->wikitext2html( $pageConfig, [
1811 'body_only' => true,
1812 'wrapSections' => $test->options['parsoid']['wrapSections'] ?? false,
1813 'traceFlags' => $this->options['traceFlags'],
1814 'dumpFlags' => $this->options['dumpFlags']
1815 ], $headers, $metadata );
1816
1817 if ( isset( $test->options['nohtml'] ) ) {
1818 // Suppress HTML (presumably because we want to test the metadata)
1819 $origOut = '';
1820 }
1821
1822 $metadataExpected = self::getParsoidMetadataSection( $test );
1823 $metadataActual = null;
1824 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
1825 $this->addParserOutputInfo(
1826 $origOut, $metadata, $test->options,
1827 $pageConfig->getLinkTarget(),
1828 $metadataExpected, $metadataActual
1829 );
1830
1831 $test->cachedBODYstr = $origOut;
1832
1833 $testResult = $this->processResults(
1834 $test, $mode,
1835 // Passing 'null' for expected output here asks normalizeHTML
1836 // to look it up for us, based on parsoid-only & standalone status
1837 isset( $test->options['nohtml'] ) ? '' : null,
1838 $origOut, [ $test, "normalizeHTML" ]
1839 );
1840 if ( $metadataExpected !== null && !$mode->isCachingMode() ) {
1841 $nullNormalizer = static function ( $actual, $expected, $ignore ) {
1842 return [ $actual, $expected ];
1843 };
1844 $metadataResult = $this->processResults(
1845 $test, new ParserTestMode( 'metadata' ), $metadataExpected, $metadataActual ?? '', $nullNormalizer
1846 );
1847 if ( $testResult === false || $testResult->isSuccess() ) {
1848 // Ensure both results have to be successful
1849 $testResult = $metadataResult;
1850 }
1851 }
1852 return $testResult;
1853 }
1854
1855 /**
1856 * @param Parsoid $parsoid
1857 * @param PageConfig $pageConfig
1858 * @param ParserTest $test
1859 * @param ParserTestMode $mode
1860 * @return ParserTestResult|false false if skipped
1861 */
1862 private function wt2wt( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
1863 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
1864 if ( $html === null ) {
1865 // We currently don't run this in standalone mode.
1866 // The expectation is to add html/parsoid sections
1867 // if we want to run these tests.
1868 return false;
1869 }
1870
1871 Assert::invariant(
1872 $test->wikitext !== null,
1873 "All tests include a wikitext section"
1874 );
1875
1876 // Handle a 'changes' option if present.
1877 $doc = $this->fetchCachedDoc( $parsoid, $pageConfig, $test );
1878 $testManualChanges = $test->options['parsoid']['changes'] ?? null;
1879 if ( $testManualChanges ) {
1880 $test->applyManualChanges( $doc );
1881 }
1882
1883 $origWT = $parsoid->dom2wikitext( $pageConfig, $doc );
1884 if ( isset( $test->options['parsoid']['changes'] ) ) {
1885 $expectedWT = $test->sections['wikitext/edited'];
1886 } else {
1887 $expectedWT = $test->wikitext;
1888 }
1889
1890 return $this->processResults(
1891 $test, $mode, $expectedWT, $origWT, [ $test, "normalizeWT" ]
1892 );
1893 }
1894
1895 /**
1896 * @param Parsoid $parsoid
1897 * @param PageConfig $pageConfig
1898 * @param ParserTest $test
1899 * @param ParserTestMode $mode
1900 * @return ParserTestResult|false false if skipped
1901 */
1902 private function html2wt( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
1903 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
1904 if ( $html === null ) {
1905 // Although ::getTestSkipMessage checks that parsoid-only tests
1906 // have html sections, this test would have (eg) only an
1907 // html/parsoid+standalone section, and we're executing in
1908 // integrated mode.
1909 return false; // Skip. Nothing to test.
1910 }
1911 if ( $test->wikitext === null && !$mode->isCachingMode() ) {
1912 // If mode is 'cache' we're executing this in order to
1913 // set cachedWTstr.
1914 throw new RuntimeException( 'Error in the test setup' );
1915 }
1916
1917 $test->cachedWTstr = $origWT = $parsoid->html2wikitext( $pageConfig, $html );
1918
1919 return $this->processResults(
1920 $test, $mode, $test->wikitext ?? '', $origWT, [ $test, "normalizeWT" ]
1921 );
1922 }
1923
1924 /**
1925 * @param Parsoid $parsoid
1926 * @param PageConfig $pageConfig
1927 * @param ParserTest $test
1928 * @param ParserTestMode $mode
1929 * @return ParserTestResult|false false if skipped
1930 */
1931 private function html2html( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
1932 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
1933 if ( $html === null ) {
1934 // Although ::getTestSkipMessage checks that parsoid-only tests
1935 // have html sections, this test would have (eg) only an
1936 // html/parsoid+standalone section, and we're executing in
1937 // integrated mode.
1938 return false; // Skip. Nothing to test.
1939 }
1940
1941 $wt = $this->fetchCachedWt( $parsoid, $pageConfig, $test );
1942
1943 // Construct a fresh PageConfig object with $wt
1944 $oldWt = $test->wikitext;
1945 $test->wikitext = $wt;
1946 $pageConfig = $this->setupParserOptionsAndBuildPageConfig( $test );
1947 $test->wikitext = $oldWt;
1948
1949 $newHtml = $parsoid->wikitext2html( $pageConfig, [
1950 'body_only' => true,
1951 'wrapSections' => $test->options['parsoid']['wrapSections'] ?? false,
1952 ] );
1953
1954 return $this->processResults(
1955 $test, $mode, $test->cachedNormalizedHTML, $newHtml, [ $test, "normalizeHTML" ]
1956 );
1957 }
1958
1959 /**
1960 * @param Parsoid $parsoid
1961 * @param PageConfig $pageConfig
1962 * @param ParserTest $test
1963 * @param ParserTestMode $mode
1964 * @return ParserTestResult|false false if skipped
1965 */
1966 private function selser( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
1967 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
1968 if ( $html === null ) {
1969 // We currently don't run this in standalone mode.
1970 // The expectation is to add html/parsoid sections
1971 // if we want to run these tests.
1972 return false;
1973 }
1974
1975 Assert::invariant(
1976 $test->wikitext !== null,
1977 "All tests include a wikitext section"
1978 );
1979
1980 if ( $test->changetree === [ 'manual' ] && !isset( $test->options['parsoid']['changes'] ) ) {
1981 throw new RuntimeException( 'Error in the test setup!' );
1982 }
1983
1984 // Apply edits to the HTML.
1985 // Always serialize to string and reparse before passing to selser/wt2wt.
1986 $doc = $this->fetchCachedDoc( $parsoid, $pageConfig, $test );
1987 if ( $test->changetree === [ 'manual' ] ) {
1988 $test->applyManualChanges( $doc );
1989 $expectedWT = $test->sections['wikitext/edited'];
1990 } else {
1991 // $test->changetree === [ 5 ]
1992 $changetree = $test->changetree;
1993 '@phan-var array $changetree'; // assert that this is not null
1994 $test->applyChanges( [], $doc, $changetree );
1995 $expectedWT = $test->wikitext;
1996 }
1997 $editedHTML = ContentUtils::toXML( DOMCompat::getBody( $doc ) );
1998
1999 // Run selser on edited doc
2000 $selserData = new SelserData( $test->wikitext, $test->cachedBODYstr );
2001 $origWT = $parsoid->html2wikitext( $pageConfig, $editedHTML, [], $selserData );
2002
2003 if ( $test->changetree === [ 5 ] ) {
2004 $origWT = preg_replace( '/<!--' . ParserTest::STATIC_RANDOM_STRING . '-->/', '', $origWT );
2005 }
2006
2007 return $this->processResults(
2008 $test, $mode, $expectedWT, $origWT, [ $test, "normalizeWT" ]
2009 );
2010 }
2011
2012 /**
2013 * @param Parsoid $parsoid
2014 * @param PageConfig $pageConfig
2015 * @param ParserTest $test
2016 * @param ParserTestMode $mode
2017 * @param Document $doc
2018 * @return array
2019 */
2020 private function runSelserEditTest(
2021 Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode, Document $doc
2022 ): array {
2023 $test->applyChanges( [], $doc, $test->changetree );
2024 $editedHTML = ContentUtils::toXML( DOMCompat::getBody( $doc ) );
2025
2026 // Run selser on edited doc
2027 $selserData = new SelserData( $test->wikitext, $test->cachedBODYstr );
2028 $origWT = $parsoid->html2wikitext( $pageConfig, $editedHTML, [], $selserData );
2029
2030 $ptResult = $this->processResults(
2031 $test, $mode,
2032 static function () use ( $parsoid, $pageConfig, $editedHTML ): string {
2033 return $parsoid->html2wikitext( $pageConfig, $editedHTML );
2034 },
2035 $origWT, [ $test, "normalizeWT" ]
2036 );
2037
2038 return [ $ptResult->actual, $ptResult->expected ];
2039 }
2040
2041 /**
2042 * @param Parsoid $parsoid
2043 * @param PageConfig $pageConfig
2044 * @param ParserTest $test
2045 * @param ParserTestMode $mode
2046 * @return ParserTestResult|false false if skipped
2047 */
2048 private function selserAutoEdit( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
2049 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
2050 if ( $html === null ) {
2051 // We currently don't run this in standalone mode.
2052 // The expectation is to add html/parsoid sections
2053 // if we want to run these tests.
2054 return false;
2055 }
2056 Assert::invariant(
2057 $test->wikitext !== null,
2058 "All tests include a wikitext section"
2059 );
2060
2061 // Apply edits to the HTML.
2062 // Always serialize to string and reparse before passing to selser/wt2wt.
2063 $doc = $this->fetchCachedDoc( $parsoid, $pageConfig, $test );
2064 if ( !$test->changetree ) {
2065 $test->changetree = $test->generateChanges( $doc );
2066 if ( !$test->changetree ) {
2067 // No more changes to make
2068 return false;
2069 }
2070 $mode = new ParserTestMode( 'selser', $test->changetree );
2071 }
2072 [ $out, $expected ] = $this->runSelserEditTest( $parsoid, $pageConfig, $test, $mode, $doc );
2073 return new ParserTestResult( $test, $mode, $expected, $out );
2074 }
2075
2076 /**
2077 * @param Parsoid $parsoid
2078 * @param PageConfig $pageConfig
2079 * @param ParserTest $test
2080 * @param ParserTestMode $mode
2081 * @return ParserTestResult|false false if skipped
2082 */
2083 private function selserAutoEditComposite( Parsoid $parsoid, PageConfig $pageConfig, ParserTest $test, ParserTestMode $mode ) {
2084 $html = $test->sections['html/parsoid+integrated'] ?? $test->parsoidHtml;
2085 if ( $html === null ) {
2086 // We currently don't run this in standalone mode.
2087 // The expectation is to add html/parsoid sections
2088 // if we want to run these tests.
2089 return false;
2090 }
2091 Assert::invariant(
2092 $test->wikitext !== null,
2093 "All tests include a wikitext section"
2094 );
2095
2096 if ( $test->changetree ) {
2097 // Apply edits to the HTML.
2098 // Always serialize to string and reparse before passing to selser/wt2wt.
2099 $doc = $this->fetchCachedDoc( $parsoid, $pageConfig, $test );
2100 Assert::invariant(
2101 $mode->changetree === $test->changetree,
2102 "changetree should be consistent with mode"
2103 );
2104 [ $out, $expected ] = $this->runSelserEditTest( $parsoid, $pageConfig, $test, $mode, $doc );
2105 return new ParserTestResult( $test, $mode, $expected, $out );
2106 } else {
2107 // this mode is a composite of multiple selser tests
2108 $mode = new ParserTestMode( "selserAutoEdits" );
2109 $runnerOpts = $this->getOptions();
2110 $numChanges = $runnerOpts['numchanges'] ?: 20; // default in Parsoid
2111 $bufOut = "";
2112 $bufExpected = "";
2113 for ( $i = 0; $i < $numChanges; $i++ ) {
2114 // Apply edits to the HTML.
2115 // Always serialize to string and reparse before passing to selser/wt2wt.
2116 $doc = $this->fetchCachedDoc( $parsoid, $pageConfig, $test );
2117 $test->seed = $i . '';
2118 $test->changetree = $test->generateChanges( $doc );
2119 if ( $test->changetree ) {
2120 // new mode with the generated changetree
2121 $nmode = new ParserTestMode( 'selser', $test->changetree );
2122 [ $out, $expected ] = $this->runSelserEditTest( $parsoid, $pageConfig, $test, $nmode, $doc );
2123 $testTitle = "TEST: {$test->testName} ($nmode)\n";
2124 $bufOut .= $testTitle;
2125 $bufExpected .= $testTitle;
2126 $bufOut .= "RESULT: $out\n";
2127 $bufExpected .= "RESULT: $expected\n";
2128 }
2129 // $test->changetree can be [] which is a NOP for testing
2130 // but not a NOP for duplicate change tree tests.
2131 if ( $test->isDuplicateChangeTree( $test->changetree ) ) {
2132 // Once we get a duplicate change tree, we can no longer
2133 // generate and run new tests. So, be done now!
2134 break;
2135 } else {
2136 $test->selserChangeTrees[$i] = $test->changetree;
2137 }
2138 }
2139 return new ParserTestResult( $test, $mode, $bufExpected, $bufOut );
2140 }
2141 }
2142
2143 private function setupParserOptionsAndBuildPageConfig( ParserTest $test ): PageConfig {
2144 $services = MediaWikiServices::getInstance();
2145 $pageConfigFactory = $services->get( 'ParsoidPageConfigFactory' );
2146 $pageConfig = null;
2147 $runner = $this;
2148 $this->setupParserOptions(
2149 $test,
2150 static function ( $context, $title, $revProps ) use ( $runner, $pageConfigFactory, &$pageConfig ) {
2151 $user = $context->getUser();
2152 $revRecord = $revProps['rev'] ?? null;
2153 if ( !$revRecord ) {
2154 // Unlike the legacy parser which doesn't need an actual revrecord to parse
2155 // wikitext, Parsoid creates a PageConfig which needs an actual revrecord.
2156 // So create a fake mutable on here.
2157 $revRecord = $runner->createRevRecord( $title, $user, $revProps );
2158 }
2159 $page = MediaWikiServices::getInstance()->getTitleFactory()->newFromLinkTarget( $title );
2160 $pageConfig = $pageConfigFactory->create(
2161 $page, $user, $revRecord, null, null
2162 );
2163 return $pageConfig->getParserOptions();
2164 } );
2165 '@phan-var PageConfig $pageConfig'; // assert that this is not null
2166 return $pageConfig;
2167 }
2168
2169 /**
2170 * Helper function to register a Parsoid extension module in such a
2171 * way that it can be cleaned up after the test is complete.
2172 * @param SiteConfig $siteConfig
2173 * @param class-string<ExtensionModule> $moduleName
2174 * @return callable
2175 */
2176 private static function registerExtensionModule( SiteConfig $siteConfig, string $moduleName ): callable {
2177 $id = $siteConfig->registerExtensionModule( $moduleName );
2178 return static function () use ( $siteConfig, $id ) {
2179 $siteConfig->unregisterExtensionModule( $id );
2180 };
2181 }
2182
2183 /**
2184 * Run a given wikitext input through a freshly-constructed Parsoid parser,
2185 * running in 'integrated' mode, and compare the output against the
2186 * expected results.
2187 *
2188 * Prints status and explanatory messages to stdout.
2189 *
2190 * staticSetup() and setupWikiData() must be called before this function
2191 * is entered.
2192 *
2193 * @param ParserTest $test The test parameters:
2194 * @param ParserTestMode $mode Parsoid test mode to run (including specific
2195 * changetree to run selser test in, if applicable)
2196 *
2197 * @return ParserTestResult|false false if skipped
2198 */
2199 public function runParsoidTest( ParserTest $test, ParserTestMode $mode ) {
2200 wfDebug( __METHOD__ . ": running {$test->testName} [$mode]" );
2201 $opts = $test->options;
2202
2203 // Skip tests targetting features Parsoid doesn't (yet) support
2204 // @todo T270312
2205 if ( isset( $opts['styletag'] ) || isset( $opts['pst'] ) ||
2206 isset( $opts['msg'] ) || isset( $opts['section'] ) ||
2207 isset( $opts['replace'] ) || isset( $opts['comment'] ) ||
2208 isset( $opts['preload'] )
2209 ) {
2210 return false;
2211 }
2212
2213 $teardownGuard = $this->perTestSetup( $test );
2214 $pageConfig = $this->setupParserOptionsAndBuildPageConfig( $test );
2215
2216 $teardown = [];
2217
2218 // Register any special extensions required by this test case
2219 $services = MediaWikiServices::getInstance();
2220 $siteConfig = $services->get( 'ParsoidSiteConfig' );
2221 $siteConfig->getLogger()->log( 'debug', "\n------ LOGS for {$test->testName} [$mode] ------" );
2222 $teardown[] = self::registerExtensionModule( $siteConfig, ParsoidParserHook::class );
2223 if ( ( $test->options['wgrawhtml'] ?? null ) === '1' ) {
2224 $teardown[] = self::registerExtensionModule( $siteConfig, ParsoidRawHTML::class );
2225 }
2226 if ( isset( $test->options['styletag'] ) ) {
2227 $teardown[] = self::registerExtensionModule( $siteConfig, ParsoidStyleTag::class );
2228 }
2229 // unregister these after this test
2230 $teardownGuard = $this->createTeardownObject( $teardown, $teardownGuard );
2231
2232 // Create the Parsoid object. (This is cheap, since the SiteConfig
2233 // and DataAccess are cached by the ServiceContainer.)
2234 $dataAccess = $services->get( 'ParsoidDataAccess' );
2235 $parsoid = new Parsoid( $siteConfig, $dataAccess );
2236 switch ( $mode->mode ) {
2237 case 'wt2html':
2238 case 'wt2html+integrated':
2239 $res = $this->wt2html( $parsoid, $pageConfig, $test, $mode );
2240 break;
2241
2242 case 'wt2wt':
2243 $res = $this->wt2wt( $parsoid, $pageConfig, $test, $mode );
2244 break;
2245
2246 case 'html2wt':
2247 $res = $this->html2wt( $parsoid, $pageConfig, $test, $mode );
2248 break;
2249
2250 case 'html2html':
2251 $res = $this->html2html( $parsoid, $pageConfig, $test, $mode );
2252 break;
2253
2254 case 'selser':
2255 $test->changetree = $mode->changetree;
2256 $res = $this->selser( $parsoid, $pageConfig, $test, $mode );
2257 $test->changetree = null; // Reset after each selser test
2258 break;
2259
2260 case 'selser-auto-composite':
2261 $test->changetree = $mode->changetree;
2262 $res = $this->selserAutoEditComposite( $parsoid, $pageConfig, $test, $mode );
2263 $test->changetree = null; // Reset after each selser test
2264 break;
2265
2266 case 'selser-auto':
2267 $test->changetree = $mode->changetree;
2268 $res = $this->selserAutoEdit( $parsoid, $pageConfig, $test, $mode );
2269 if ( $res === false && !$test->changetree ) {
2270 // TEMPORARY HACK
2271 // If we don't run any selser tests, ensure changetree is not null
2272 // because we are going to call Test::isDuplicateChangeTree() on it
2273 // This ensures that we continue to crash if change tree is null
2274 // for any other reason!
2275 $test->changetree = [];
2276 }
2277 // Don't reset changetree here -- it is used to detect duplicate trees
2278 // and stop selser test generation in Test.php::testAllModes
2279 break;
2280
2281 default:
2282 // Unsupported Mode
2283 $res = false;
2284 break;
2285 }
2286
2287 ScopedCallback::consume( $teardownGuard );
2288 return $res;
2289 }
2290
2291 /**
2292 * Use a regex to find out the value of an option
2293 * @param string $key Name of option val to retrieve
2294 * @param array $opts Options array to look in
2295 * @param mixed $default Default value returned if not found
2296 * @return mixed
2297 */
2298 private static function getOptionValue( $key, $opts, $default ) {
2299 $key = strtolower( $key );
2300 return $opts[$key] ?? $default;
2301 }
2302
2303 /**
2304 * Do any required setup which is dependent on test options.
2305 *
2306 * @see staticSetup() for more information about setup/teardown
2307 *
2308 * @param ParserTest $test Test info supplied by TestFileReader
2309 * @param callable|null $nextTeardown
2310 * @return ScopedCallback
2311 */
2312 public function perTestSetup( ParserTest $test, $nextTeardown = null ) {
2313 $teardown = [];
2314
2315 $this->checkSetupDone( 'setupDatabase' );
2316 $teardown[] = $this->markSetupDone( 'perTestSetup' );
2317
2318 $opts = $test->options;
2319 $mwServices = MediaWikiServices::getInstance();
2320
2321 // Find out values for some special options.
2322 $langCode =
2323 self::getOptionValue( 'language', $opts, 'en' );
2324 $variant = // old deprecated option name
2325 self::getOptionValue( 'variant', $opts, false );
2326 $variant =
2327 self::getOptionValue( 'htmlVariantLanguage', $opts, $variant );
2328 $maxtoclevel =
2329 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
2330 $linkHolderBatchSize =
2331 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
2332 $timezone =
2333 self::getOptionValue( 'wgLocaltimezone', $opts, 'UTC' );
2334
2335 $setup = [
2336 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
2337 'wgLanguageCode' => $langCode,
2338 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
2339 'wgNamespacesWithSubpages' => array_fill_keys(
2340 $mwServices->getNamespaceInfo()->getValidNamespaces(),
2341 isset( $opts['subpage'] )
2342 ),
2343 'wgMaxTocLevel' => $maxtoclevel,
2344 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
2345 'wgThumbLimits' => [ 0, 0, 0, 0, 0, self::getOptionValue( 'thumbsize', $opts, 180 ) ],
2346 'wgDefaultLanguageVariant' => $variant,
2347 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
2348 // Set as a JSON object like:
2349 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
2350 'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
2351 + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
2352 // Test with legacy encoding by default until HTML5 is very stable and default
2353 'wgFragmentMode' => [ 'legacy' ],
2354 // Use legacy headings for a while until tests in extensions are updated
2355 'wgParserEnableLegacyHeadingDOM' => true,
2356 'wgLocaltimezone' => $timezone,
2357 ];
2358
2359 if ( isset( $opts['externallinktarget'] ) ) {
2360 $setup['wgExternalLinkTarget'] = self::getOptionValue( 'externallinktarget', $opts, '' );
2361 }
2362
2363 $nonIncludable = self::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
2364 if ( $nonIncludable !== false ) {
2365 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
2366 }
2367
2368 if ( $test->config ) {
2369 foreach ( $test->config as $var => $value ) {
2370 $setup[$var] = $value;
2371 }
2372 }
2373
2374 /** @since 1.20 */
2375 ( new HookRunner( $mwServices->getHookContainer() ) )->onParserTestGlobals( $setup );
2376
2377 // Take care of the content language and variant
2378 $resetVariant = $variant !== false || isset( $test->config['wgUsePigLatinVariant'] );
2379 if ( $langCode !== 'en' || $resetVariant ) {
2380 $this->resetLanguageServices( $setup, $teardown, $resetVariant );
2381 }
2382
2383 // Other services that can be configured per test
2384 $reset = function () use ( $mwServices ) {
2385 // Configurations changed above
2386 $this->resetTitleServices();
2387 $mwServices->resetServiceForTesting( 'MagicWordFactory' );
2388 $mwServices->resetServiceForTesting( 'ParserFactory' );
2389 // Depends on $wgParserEnableLegacyMediaDOM
2390 $mwServices->resetServiceForTesting( 'Tidy' );
2391 // Depends on $wgParserEnableLegacyHeadingDOM
2392 $mwServices->resetServiceForTesting( 'DefaultOutputPipeline' );
2393 // The SiteConfig depends on various services that reset above,
2394 // so reset it as well.
2395 // T310283: be more selective about resetting SiteConfig if
2396 // performance is a concern.
2397 $mwServices->resetServiceForTesting( 'ParsoidSiteConfig' );
2398 // Depends on the legacy ParserFactory
2399 $mwServices->resetServiceForTesting( 'ParsoidDataAccess' );
2400 };
2401 $setup[] = $reset;
2402 $teardown[] = $reset;
2403
2404 // Clear language conversion tables
2405 $teardown[] = static function () use ( $mwServices, $langCode ) {
2406 $lang = $mwServices->getLanguageFactory()->getLanguage( $langCode );
2407 $wrapper = TestingAccessWrapper::newFromObject(
2408 $mwServices->getLanguageConverterFactory()
2409 ->getLanguageConverter( $lang )
2410 );
2411 @$wrapper->reloadTables();
2412 };
2413
2414 // Reset OOUI auto-increment IDs (T345515)
2415 OOUI\Tag::resetElementId();
2416
2417 $teardown[] = $this->executeSetupSnippets( $setup );
2418
2419 return $this->createTeardownObject( $teardown, $nextTeardown );
2420 }
2421
2422 private function resetLanguageServices( array &$setup, array &$teardown, $resetVariant = false ) {
2423 $mwServices = MediaWikiServices::getInstance();
2424 $reset = static function () use ( $mwServices, $resetVariant ) {
2425 $mwServices->resetServiceForTesting( 'ContentLanguage' );
2426
2427 if ( $resetVariant ) {
2428 // If !!config touches $wgUsePigLatinVariant, these need to be reset
2429 $mwServices->resetServiceForTesting( 'LanguageConverterFactory' );
2430 $mwServices->resetServiceForTesting( 'LanguageFactory' );
2431 $mwServices->resetServiceForTesting( 'LanguageNameUtils' );
2432 $mwServices->resetServiceForTesting( 'LocalisationCache' );
2433 }
2434
2435 // Content language invalidates a lot of services.
2436 $mwServices->resetServiceForTesting( 'UserOptionsManager' );
2437 $mwServices->resetServiceForTesting( 'UserOptionsLookup' );
2438 $mwServices->resetServiceForTesting( 'MessageCache' );
2439
2440 // Purge the cached Language object
2441 $context = RequestContext::getMain();
2442 $context->setUser( $context->getUser() );
2443 };
2444 $setup[] = $reset;
2445 $teardown[] = $reset;
2446 }
2447
2448 /**
2449 * Set up temporary DB tables.
2450 *
2451 * For best performance, call this once only for all tests. However, it can
2452 * be called at the start of each test if more isolation is desired.
2453 *
2454 *
2455 * Do not call this function from a MediaWikiIntegrationTestCase subclass,
2456 * since MediaWikiIntegrationTestCase does its own DB setup.
2457 *
2458 * @see staticSetup() for more information about setup/teardown
2459 *
2460 * @param ScopedCallback|null $nextTeardown The next teardown object
2461 * @return ScopedCallback The teardown object
2462 */
2463 public function setupDatabase( $nextTeardown = null ) {
2464 global $wgDBprefix;
2465
2466 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2467 $this->db = $lb->getConnectionInternal( DB_PRIMARY );
2468
2469 $suspiciousPrefixes = [ self::DB_PREFIX, MediaWikiIntegrationTestCase::DB_PREFIX ];
2470 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
2471 throw new RuntimeException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
2472 }
2473
2474 $teardown = [];
2475 $teardown[] = $this->markSetupDone( 'setupDatabase' );
2476
2477 // Set up a test DB just for parser tests
2478 MediaWikiIntegrationTestCase::setupAllTestDBs(
2479 $this->db,
2480 self::DB_PREFIX,
2481 true // postgres requires that we use temporary tables
2482 );
2483 MediaWikiIntegrationTestCase::resetNonServiceCaches();
2484 $teardown[] = static function () {
2485 MediaWikiIntegrationTestCase::teardownTestDB();
2486 };
2487
2488 MediaWikiIntegrationTestCase::installMockMwServices();
2489 $teardown[] = static function () {
2490 MediaWikiIntegrationTestCase::restoreMwServices();
2491 };
2492
2493 // Wipe some DB query result caches on setup and teardown
2494 $reset = static function () {
2495 $services = MediaWikiServices::getInstance();
2496 $services->getLinkCache()->clear();
2497
2498 // Clear the message cache
2499 $services->getMessageCache()->clear();
2500 };
2501 $reset();
2502 $teardown[] = $reset;
2503 return $this->createTeardownObject( $teardown, $nextTeardown );
2504 }
2505
2506 /**
2507 * Add data about uploads to the new test DB, and set up the upload
2508 * directory. This should be called after setupDatabase().
2509 *
2510 * @param ScopedCallback|null $nextTeardown The next teardown object
2511 * @return ScopedCallback The teardown object
2512 */
2513 public function setupUploads( $nextTeardown = null ) {
2514 $teardown = [];
2515
2516 $this->checkSetupDone( 'setupDatabase' );
2517 $teardown[] = $this->markSetupDone( 'setupUploads' );
2518
2519 // Create the files in the upload directory (or pretend to create them
2520 // in a MockFileBackend). Append teardown callback.
2521 $teardown[] = $this->setupUploadBackend();
2522
2523 // Create a authority
2524 $performer = new UltimateAuthority( new UserIdentityValue( 0, User::MAINTENANCE_SCRIPT_USER ) );
2525
2526 // Register the uploads in the database
2527 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2528
2529 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Foobar.jpg' ) );
2530 # note that the size/width/height/bits/etc of the file
2531 # are actually set by inspecting the file itself; the arguments
2532 # to recordUpload3 have no effect. That said, we try to make things
2533 # match up so it is less confusing to readers of the code & tests.
2534 $image->recordUpload3(
2535 '',
2536 'Upload of some lame file', 'Some lame file',
2537 $performer,
2538 [
2539 'size' => 7881,
2540 'width' => 1941,
2541 'height' => 220,
2542 'bits' => 8,
2543 'media_type' => MEDIATYPE_BITMAP,
2544 'mime' => 'image/jpeg',
2545 'metadata' => [],
2546 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
2547 'fileExists' => true
2548 ],
2549 $this->db->timestamp( '20010115123500' )
2550 );
2551
2552 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Thumb.png' ) );
2553 # again, note that size/width/height below are ignored; see above.
2554 $image->recordUpload3(
2555 '',
2556 'Upload of some lame thumbnail',
2557 'Some lame thumbnail',
2558 $performer,
2559 [
2560 'size' => 22589,
2561 'width' => 135,
2562 'height' => 135,
2563 'bits' => 8,
2564 'media_type' => MEDIATYPE_BITMAP,
2565 'mime' => 'image/png',
2566 'metadata' => [],
2567 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
2568 'fileExists' => true
2569 ],
2570 $this->db->timestamp( '20130225203040' )
2571 );
2572
2573 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Foobar.svg' ) );
2574 $image->recordUpload3(
2575 '',
2576 'Upload of some lame SVG',
2577 'Some lame SVG',
2578 $performer,
2579 [
2580 'size' => 12345,
2581 'width' => 240,
2582 'height' => 180,
2583 'bits' => 0,
2584 'media_type' => MEDIATYPE_DRAWING,
2585 'mime' => 'image/svg+xml',
2586 'metadata' => [
2587 'version' => SvgHandler::SVG_METADATA_VERSION,
2588 'width' => 240,
2589 'height' => 180,
2590 'originalWidth' => '100%',
2591 'originalHeight' => '100%',
2592 'translations' => [
2593 'en' => SVGReader::LANG_FULL_MATCH,
2594 'ru' => SVGReader::LANG_FULL_MATCH,
2595 ],
2596 ],
2597 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
2598 'fileExists' => true
2599 ],
2600 $this->db->timestamp( '20010115123500' )
2601 );
2602
2603 # This image will be prohibited via the list in [[MediaWiki:Bad image list]]
2604 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Bad.jpg' ) );
2605 $image->recordUpload3(
2606 '',
2607 'zomgnotcensored',
2608 'Borderline image',
2609 $performer,
2610 [
2611 'size' => 12345,
2612 'width' => 320,
2613 'height' => 240,
2614 'bits' => 24,
2615 'media_type' => MEDIATYPE_BITMAP,
2616 'mime' => 'image/jpeg',
2617 'metadata' => [],
2618 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
2619 'fileExists' => true
2620 ],
2621 $this->db->timestamp( '20010115123500' )
2622 );
2623
2624 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Hi-ho.jpg' ) );
2625 $image->recordUpload3(
2626 '',
2627 'Hi',
2628 'ho',
2629 $performer,
2630 [
2631 'size' => 7881,
2632 'width' => 1941,
2633 'height' => 220,
2634 'bits' => 8,
2635 'media_type' => MEDIATYPE_BITMAP,
2636 'mime' => 'image/jpeg',
2637 'metadata' => [],
2638 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
2639 'fileExists' => true
2640 ],
2641 $this->db->timestamp( '20010115123500' )
2642 );
2643
2644 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Video.ogv' ) );
2645 $image->recordUpload3(
2646 '',
2647 'A pretty movie',
2648 'Will it play',
2649 $performer,
2650 [
2651 'size' => 12345,
2652 'width' => 320,
2653 'height' => 240,
2654 'bits' => 0,
2655 'media_type' => MEDIATYPE_VIDEO,
2656 'mime' => 'application/ogg',
2657 'metadata' => [],
2658 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
2659 'fileExists' => true
2660 ],
2661 $this->db->timestamp( '20010115123500' )
2662 );
2663
2664 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'Audio.oga' ) );
2665 $image->recordUpload3(
2666 '',
2667 'An awesome hitsong',
2668 'Will it play',
2669 $performer,
2670 [
2671 'size' => 12345,
2672 'width' => 0,
2673 'height' => 0,
2674 'bits' => 0,
2675 'media_type' => MEDIATYPE_AUDIO,
2676 'mime' => 'application/ogg',
2677 'metadata' => [],
2678 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
2679 'fileExists' => true
2680 ],
2681 $this->db->timestamp( '20010115123500' )
2682 );
2683
2684 # A DjVu file
2685 $image = $localRepo->newFile( new TitleValue( NS_FILE, 'LoremIpsum.djvu' ) );
2686 $djvuMetadata = [
2687 'data' => [
2688 'pages' => [
2689 [ 'height' => 3508, 'width' => 2480, 'dpi' => 300, 'gamma' => 2.2 ],
2690 [ 'height' => 3508, 'width' => 2480, 'dpi' => 300, 'gamma' => 2.2 ],
2691 [ 'height' => 3508, 'width' => 2480, 'dpi' => 300, 'gamma' => 2.2 ],
2692 [ 'height' => 3508, 'width' => 2480, 'dpi' => 300, 'gamma' => 2.2 ],
2693 [ 'height' => 3508, 'width' => 2480, 'dpi' => 300, 'gamma' => 2.2 ],
2694 ],
2695 ],
2696 ];
2697 $image->recordUpload3(
2698 '',
2699 'Upload a DjVu',
2700 'A DjVu',
2701 $performer,
2702 [
2703 'size' => 3249,
2704 'width' => 2480,
2705 'height' => 3508,
2706 'bits' => 0,
2707 'media_type' => MEDIATYPE_OFFICE,
2708 'mime' => 'image/vnd.djvu',
2709 'metadata' => $djvuMetadata,
2710 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
2711 'fileExists' => true
2712 ],
2713 $this->db->timestamp( '20010115123600' )
2714 );
2715
2716 return $this->createTeardownObject( $teardown, $nextTeardown );
2717 }
2718
2719 /**
2720 * Upload test files to the backend created by createRepoGroup().
2721 *
2722 * @return callable The teardown callback
2723 */
2724 private function setupUploadBackend() {
2725 global $IP;
2726
2727 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2728 $base = $repo->getZonePath( 'public' );
2729 $backend = $repo->getBackend();
2730 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
2731 $backend->quickStore( [
2732 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
2733 'dst' => "$base/3/3a/Foobar.jpg"
2734 ] );
2735 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
2736 $backend->quickStore( [
2737 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
2738 'dst' => "$base/e/ea/Thumb.png"
2739 ] );
2740 $backend->prepare( [ 'dir' => "$base/0/09" ] );
2741 $backend->quickStore( [
2742 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
2743 'dst' => "$base/0/09/Bad.jpg"
2744 ] );
2745 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
2746 $backend->quickStore( [
2747 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
2748 'dst' => "$base/5/5f/LoremIpsum.djvu"
2749 ] );
2750
2751 // No helpful SVG file to copy, so make one ourselves
2752 $data = '<?xml version="1.0" encoding="utf-8"?>' .
2753 '<svg xmlns="http://www.w3.org/2000/svg"' .
2754 ' version="1.1" width="240" height="180"/>';
2755
2756 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
2757 $backend->quickCreate( [
2758 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
2759 ] );
2760
2761 return function () use ( $backend ) {
2762 if ( $backend instanceof MockFileBackend ) {
2763 // In memory backend, so dont bother cleaning them up.
2764 return;
2765 }
2766 $this->teardownUploadBackend();
2767 };
2768 }
2769
2770 /**
2771 * Remove the dummy uploads directory
2772 */
2773 private function teardownUploadBackend() {
2774 if ( $this->keepUploads ) {
2775 return;
2776 }
2777
2778 $public = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
2779 ->getZonePath( 'public' );
2780
2781 $this->deleteFiles(
2782 [
2783 "$public/3/3a/Foobar.jpg",
2784 "$public/e/ea/Thumb.png",
2785 "$public/0/09/Bad.jpg",
2786 "$public/5/5f/LoremIpsum.djvu",
2787 "$public/f/ff/Foobar.svg",
2788 "$public/0/00/Video.ogv",
2789 "$public/4/41/Audio.oga",
2790 ]
2791 );
2792 }
2793
2794 /**
2795 * Delete the specified files and their parent directories
2796 * @param string[] $files File backend URIs mwstore://...
2797 */
2798 private function deleteFiles( $files ) {
2799 // Delete the files
2800 $backend = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->getBackend();
2801 foreach ( $files as $file ) {
2802 $backend->quickDelete( [ 'src' => $file ], [ 'force' => 1 ] );
2803 }
2804
2805 // Delete the parent directories
2806 foreach ( $files as $file ) {
2807 $tmp = FileBackend::parentStoragePath( $file );
2808 while ( $tmp ) {
2809 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
2810 break;
2811 }
2812 $tmp = FileBackend::parentStoragePath( $tmp );
2813 }
2814 }
2815 }
2816
2817 /**
2818 * Add articles to the test DB.
2819 *
2820 * @see staticSetup() for more information about setup/teardown
2821 *
2822 * @param ParserTestArticle[] $articles Article info array from TestFileReader
2823 * @param ?ScopedCallback $nextTeardown The next teardown object
2824 * @return ScopedCallback The teardown object
2825 */
2826 public function addArticles(
2827 array $articles, ?ScopedCallback $nextTeardown = null
2828 ): ScopedCallback {
2829 $this->checkSetupDone( 'setupDatabase' );
2830 $this->checkSetupDone( 'staticSetup' );
2831
2832 foreach ( $articles as $info ) {
2833 $this->addArticle( $info->title, $info->text, $info->filename, $info->lineNumStart );
2834 }
2835
2836 $teardown = [];
2837 $services = MediaWikiServices::getInstance();
2838
2839 // Wipe WANObjectCache process cache, which is invalidated by article insertion
2840 // due to T144706
2841 $services->getMainWANObjectCache()->clearProcessCache();
2842 // Avoid reuse of lazy-loaded Title::mArticleId after page creation
2843 Title::clearCaches();
2844
2845 $reset = static function () use ( $services ) {
2846 // Reset the service so that any "MediaWiki:bad image list" articles
2847 // added get fetched
2848 $services->resetServiceForTesting( 'BadFileLookup' );
2849 // Depends on BadFileLookup, also reset here in case it no longer
2850 // depends on the legacy ParserFactory which reset per test.
2851 $services->resetServiceForTesting( 'ParsoidDataAccess' );
2852 };
2853 $reset();
2854
2855 $teardown[] = $reset;
2856 $teardown[] = function () use ( $articles ) {
2857 $this->cleanupArticles( $articles );
2858 };
2859
2860 return $this->createTeardownObject( $teardown, $nextTeardown );
2861 }
2862
2863 /**
2864 * Remove articles from the test DB. This prevents independent parser
2865 * test files from having conflicts when they choose the same names
2866 * for article or template test fixtures.
2867 *
2868 * @param ParserTestArticle[] $articles Article info array from TestFileReader
2869 */
2870 public function cleanupArticles( $articles ) {
2871 $this->checkSetupDone( 'setupDatabase' );
2872 $this->checkSetupDone( 'staticSetup' );
2873 $deleter = new UltimateAuthority( new UserIdentityValue( 0, User::MAINTENANCE_SCRIPT_USER ) );
2874 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
2875 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
2876 $delPageFactory = MediaWikiServices::getInstance()->getDeletePageFactory();
2877 foreach ( $articles as $info ) {
2878 $name = self::chomp( $info->title );
2879 $title = $titleParser->parseTitle( $name );
2880 $page = $wikiPageFactory->newFromLinkTarget( $title );
2881 $delPageFactory->newDeletePage( $page, $deleter )->deleteUnsafe( 'cleaning up' );
2882 }
2883
2884 // Clear the static cache that Title class maintains.
2885 // This ensures that Parsoid test runs that follow legacy parser test runs
2886 // don't reuse titles. This matters because it looks like legacy test run
2887 // and Parsoid test run differ in the number of articles they create in the db.
2888 // We need to investigate that separately, but given that they differ, titles
2889 // will get different article and revision ids across test runs.
2890 // While we could add this to resetTitleServices(), there is really
2891 // no reason to clear this for every test. Sufficient to clear this
2892 // once per test file.
2893 // Also the LinkCache is cleared which holds some information about titles
2894 Title::clearCaches();
2895 }
2896
2897 /**
2898 * Insert a temporary test article
2899 *
2900 * @todo Refactor to share more code w/ ::editPage
2901 *
2902 * @param string $name The title, including any prefix
2903 * @param string $text The article text
2904 * @param string $file The input file name
2905 * @param int|string $line The input line number, for reporting errors
2906 */
2907 private function addArticle( $name, $text, $file, $line ) {
2908 $text = self::chomp( $text );
2909 $name = self::chomp( $name );
2910
2911 $services = MediaWikiServices::getInstance();
2912
2913 $title = $services->getTitleParser()->parseTitle( $name );
2914 wfDebug( __METHOD__ . ": adding $name" );
2915
2916 if ( $title === null ) {
2917 throw new RuntimeException( "invalid title '$name' at $file:$line\n" );
2918 }
2919
2920 $performer = new UltimateAuthority( new UserIdentityValue( 0, User::MAINTENANCE_SCRIPT_USER ) );
2921
2922 $page = $services->getWikiPageFactory()->newFromLinkTarget( $title );
2923 $page->loadPageData( IDBAccessObject::READ_LATEST );
2924 $newContent = $page->getContentHandler()->unserializeContent( $text );
2925
2926 if ( $page->exists() ) {
2927 $content = $page->getContent( RevisionRecord::RAW );
2928 // Only reject the title, if the content/content model is different.
2929 // This makes it easier to create Template:(( or Template:)) in different extensions
2930 if ( $newContent->equals( $content ) ) {
2931 return;
2932 }
2933 throw new RuntimeException(
2934 "duplicate article '$name' with different content at $file:$line\n"
2935 );
2936 }
2937
2938 // Optionally use mock parser, to make debugging of actual parser tests simpler.
2939 // But initialise the MessageCache clone first, don't let MessageCache
2940 // get a reference to the mock object.
2941 if ( $this->disableSaveParse ) {
2942 $services->getMessageCache()->getParser();
2943 $services->disableService( 'Parser' );
2944 $services->disableService( 'ParserFactory' );
2945 $services->redefineService(
2946 'Parser',
2947 static function () {
2948 return new ParserTestMockParser;
2949 }
2950 );
2951 $restore = static function () {
2952 MediaWikiServices::getInstance()->resetServiceForTesting( 'Parser' );
2953 MediaWikiServices::getInstance()->resetServiceForTesting( 'ParserFactory' );
2954 };
2955 } else {
2956 $restore = false;
2957 }
2958 $status = null;
2959 try {
2960 $status = $page->doUserEditContent(
2961 $newContent,
2962 $performer,
2963 '',
2964 EDIT_NEW | EDIT_SUPPRESS_RC | EDIT_INTERNAL
2965 );
2966 } finally {
2967 if ( $restore ) {
2968 $restore();
2969 }
2970 }
2971
2972 if ( !$status->isOK() ) {
2973 throw new RuntimeException( $status->__toString() );
2974 }
2975
2976 // an edit always attempt to purge backlink links such as history
2977 // pages. That is unnecessary.
2978 $jobQueueGroup = $services->getJobQueueGroup();
2979 $jobQueueGroup->get( 'htmlCacheUpdate' )->delete();
2980 // WikiPages::doEditUpdates randomly adds RC purges
2981 $jobQueueGroup->get( 'recentChangesUpdate' )->delete();
2982
2983 // The RepoGroup cache is invalidated by the creation of file redirects
2984 if ( $title->inNamespace( NS_FILE ) ) {
2985 $services->getRepoGroup()->clearCache( $title );
2986 }
2987 }
2988
2989 /**
2990 * Check if a hook is installed
2991 *
2992 * @param string $name
2993 * @return bool True if tag hook is present
2994 */
2995 public function requireHook( $name ) {
2996 $parser = MediaWikiServices::getInstance()->getParser();
2997
2998 if ( preg_match( '/^[Ee]xtension:(.*)$/', $name, $matches ) ) {
2999 $extName = $matches[1];
3000 if ( ExtensionRegistry::getInstance()->isLoaded( $extName ) ) {
3001 return true;
3002 } else {
3003 $this->recorder->warning( " Skipping this test suite because it requires the '$extName' " .
3004 "extension, which isn't loaded." );
3005 return false;
3006 }
3007 }
3008 if ( in_array( $name, $parser->getTags(), true ) ) {
3009 return true;
3010 } else {
3011 $this->recorder->warning( " Skipping this test suite because it requires the '$name' hook, " .
3012 "which isn't provided by any loaded extension." );
3013 return false;
3014 }
3015 }
3016
3017 /**
3018 * Check if a function hook is installed
3019 *
3020 * @param string $name
3021 * @return bool True if function hook is present
3022 */
3023 public function requireFunctionHook( $name ) {
3024 $parser = MediaWikiServices::getInstance()->getParser();
3025
3026 if ( in_array( $name, $parser->getFunctionHooks(), true ) ) {
3027 return true;
3028 } else {
3029 $this->recorder->warning( " This test suite requires the '$name' function " .
3030 "hook extension, skipping." );
3031 return false;
3032 }
3033 }
3034
3035 /**
3036 * Fake constant timestamp to make sure time-related parser
3037 * functions give a persistent value.
3038 *
3039 * - Parser::expandMagicVariable (via ParserGetVariableValueTs hook)
3040 * - Parser::preSaveTransform (via ParserOptions)
3041 * @return int Fake constant timestamp.
3042 */
3043 private function getFakeTimestamp() {
3044 // parsed as '1970-01-01T00:02:03Z'
3045 return 123;
3046 }
3047 }