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