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