2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @ingroup Maintenance
28 * @ingroup Maintenance
32 * boolean $color whereas output should be colorized
37 * boolean $showOutput Show test output
42 * boolean $useTemporaryTables Use temporary tables for the temporary database
44 private $useTemporaryTables = true;
47 * boolean $databaseSetupDone True if the database has been set up
49 private $databaseSetupDone = false;
52 * string $oldTablePrefix Original table prefix
54 private $oldTablePrefix;
56 private $maxFuzzTestLength = 300;
57 private $fuzzSeed = 0;
58 private $memoryLimit = 50;
61 * Sets terminal colorization and diff/quick modes depending on OS and
62 * command-line options (--color and --quick).
64 public function ParserTest( $options = array() ) {
65 # Only colorize output if stdout is a terminal.
66 $this->color = !wfIsWindows() && posix_isatty( 1 );
68 if ( isset( $options['color'] ) ) {
69 switch( $options['color'] ) {
79 $this->term = $this->color
80 ? new AnsiTermColorer()
81 : new DummyTermColorer();
83 $this->showDiffs = !isset( $options['quick'] );
84 $this->showProgress = !isset( $options['quiet'] );
85 $this->showFailure = !(
86 isset( $options['quiet'] )
87 && ( isset( $options['record'] )
88 || isset( $options['compare'] ) ) ); // redundant output
90 $this->showOutput = isset( $options['show-output'] );
93 if ( isset( $options['regex'] ) ) {
94 if ( isset( $options['record'] ) ) {
95 echo "Warning: --record cannot be used with --regex, disabling --record\n";
96 unset( $options['record'] );
98 $this->regex = $options['regex'];
104 $this->setupRecorder( $options );
105 $this->keepUploads = isset( $options['keep-uploads'] );
107 if ( isset( $options['seed'] ) ) {
108 $this->fuzzSeed = intval( $options['seed'] ) - 1;
111 $this->runDisabled = isset( $options['run-disabled'] );
113 $this->hooks = array();
114 $this->functionHooks = array();
117 public function setupRecorder ( $options ) {
118 if ( isset( $options['record'] ) ) {
119 $this->recorder = new DbTestRecorder( $this );
120 $this->recorder->version = isset( $options['setversion'] ) ?
121 $options['setversion'] : SpecialVersion::getVersion();
122 } elseif ( isset( $options['compare'] ) ) {
123 $this->recorder = new DbTestPreviewer( $this );
124 } elseif ( isset( $options['upload'] ) ) {
125 $this->recorder = new RemoteTestRecorder( $this );
127 $this->recorder = new TestRecorder( $this );
132 * Remove last character if it is a newline
134 public function chomp( $s ) {
135 if ( substr( $s, -1 ) === "\n" ) {
136 return substr( $s, 0, -1 );
144 * Run a fuzz test series
145 * Draw input from a set of test files
147 function fuzzTest( $filenames ) {
148 $GLOBALS['wgContLang'] = Language::factory( 'en' );
149 $dict = $this->getFuzzInput( $filenames );
150 $dictSize = strlen( $dict );
151 $logMaxLength = log( $this->maxFuzzTestLength );
152 $this->setupDatabase();
153 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
158 $opts = ParserOptions::newFromUser( $user );
159 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
162 // Generate test input
163 mt_srand( ++$this->fuzzSeed );
164 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
166 while ( strlen( $input ) < $totalLength ) {
167 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
168 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
169 $offset = mt_rand( 0, $dictSize - $hairLength );
170 $input .= substr( $dict, $offset, $hairLength );
173 $this->setupGlobals();
174 $parser = $this->getParser();
177 $parser->parse( $input, $title, $opts );
179 } catch ( Exception $exception ) {
184 echo "Test failed with seed {$this->fuzzSeed}\n";
193 $this->teardownGlobals();
194 $parser->__destruct();
196 if ( $numTotal % 100 == 0 ) {
197 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
198 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
200 echo "Out of memory:\n";
201 $memStats = $this->getMemoryBreakdown();
202 foreach ( $memStats as $name => $usage ) {
203 echo "$name: $usage\n";
212 * Get an input dictionary from a set of parser test files
214 function getFuzzInput( $filenames ) {
216 foreach ( $filenames as $filename ) {
217 $contents = file_get_contents( $filename );
218 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
219 foreach ( $matches[1] as $match ) {
220 $dict .= $match . "\n";
227 * Get a memory usage breakdown
229 function getMemoryBreakdown() {
231 foreach ( $GLOBALS as $name => $value ) {
232 $memStats['$' . $name] = strlen( serialize( $value ) );
234 $classes = get_declared_classes();
235 foreach ( $classes as $class ) {
236 $rc = new ReflectionClass( $class );
237 $props = $rc->getStaticProperties();
238 $memStats[$class] = strlen( serialize( $props ) );
239 $methods = $rc->getMethods();
240 foreach ( $methods as $method ) {
241 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
244 $functions = get_defined_functions();
245 foreach ( $functions['user'] as $function ) {
246 $rf = new ReflectionFunction( $function );
247 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
258 * Run a series of tests listed in the given text files.
259 * Each test consists of a brief description, wikitext input,
260 * and the expected HTML output.
262 * Prints status updates on stdout and counts up the total
263 * number and percentage of passed tests.
265 * @param $filenames Array of strings
266 * @return Boolean: true if passed all tests, false if any tests failed.
268 public function runTestsFromFiles( $filenames ) {
269 $GLOBALS['wgContLang'] = Language::factory( 'en' );
270 $this->recorder->start();
271 $this->setupDatabase();
273 foreach ( $filenames as $filename ) {
274 $tests = new TestFileIterator( $filename, $this );
275 $ok = $this->runTests( $tests ) && $ok;
277 $this->teardownDatabase();
278 $this->recorder->report();
279 $this->recorder->end();
283 function runTests( $tests ) {
285 foreach ( $tests as $i => $t ) {
287 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
288 $ok = $ok && $result;
289 $this->recorder->record( $t['test'], $result );
291 if ( $this->showProgress ) {
298 * Get a Parser object
300 function getParser( $preprocessor = null ) {
301 global $wgParserConf;
302 $class = $wgParserConf['class'];
303 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
304 foreach ( $this->hooks as $tag => $callback ) {
305 $parser->setHook( $tag, $callback );
307 foreach ( $this->functionHooks as $tag => $bits ) {
308 list( $callback, $flags ) = $bits;
309 $parser->setFunctionHook( $tag, $callback, $flags );
311 wfRunHooks( 'ParserTestParser', array( &$parser ) );
316 * Run a given wikitext input through a freshly-constructed wiki parser,
317 * and compare the output against the expected results.
318 * Prints status and explanatory messages to stdout.
320 * @param $desc String: test's description
321 * @param $input String: wikitext to try rendering
322 * @param $result String: result to output
323 * @param $opts Array: test's options
324 * @param $config String: overrides for global variables, one per line
327 public function runTest( $desc, $input, $result, $opts, $config ) {
328 if ( $this->showProgress ) {
329 $this->showTesting( $desc );
332 $opts = $this->parseOptions( $opts );
333 $this->setupGlobals( $opts, $config );
336 $options = ParserOptions::newFromUser( $user );
339 if ( isset( $opts['title'] ) ) {
340 $titleText = $opts['title'];
343 $titleText = 'Parser test';
346 $noxml = isset( $opts['noxml'] );
347 $local = isset( $opts['local'] );
348 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
349 $parser = $this->getParser( $preprocessor );
350 $title = Title::newFromText( $titleText );
353 if ( isset( $opts['pst'] ) ) {
354 $out = $parser->preSaveTransform( $input, $title, $user, $options );
355 } elseif ( isset( $opts['msg'] ) ) {
356 $out = $parser->transformMsg( $input, $options );
357 } elseif ( isset( $opts['section'] ) ) {
358 $section = $opts['section'];
359 $out = $parser->getSection( $input, $section );
360 } elseif ( isset( $opts['replace'] ) ) {
361 $section = $opts['replace'][0];
362 $replace = $opts['replace'][1];
363 $out = $parser->replaceSection( $input, $section, $replace );
364 } elseif ( isset( $opts['comment'] ) ) {
365 $linker = $user->getSkin();
366 $out = $linker->formatComment( $input, $title, $local );
367 } elseif ( isset( $opts['preload'] ) ) {
368 $out = $parser->getpreloadText( $input, $title, $options );
370 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
371 $out = $output->getText();
373 if ( isset( $opts['showtitle'] ) ) {
374 if ( $output->getTitleText() ) $title = $output->getTitleText();
375 $out = "$title\n$out";
377 if ( isset( $opts['ill'] ) ) {
378 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
379 } elseif ( isset( $opts['cat'] ) ) {
381 $wgOut->addCategoryLinks( $output->getCategories() );
382 $cats = $wgOut->getCategoryLinks();
383 if ( isset( $cats['normal'] ) ) {
384 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
390 $result = $this->tidy( $result );
394 $this->teardownGlobals();
396 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
397 return $this->showSuccess( $desc );
399 return $this->showFailure( $desc, $result, $out );
405 * Use a regex to find out the value of an option
406 * @param $key String: name of option val to retrieve
407 * @param $opts Options array to look in
408 * @param $default Mixed: default value returned if not found
410 private static function getOptionValue( $key, $opts, $default ) {
411 $key = strtolower( $key );
412 if ( isset( $opts[$key] ) ) {
419 private function parseOptions( $instring ) {
421 $lines = explode( "\n", $instring );
426 // foo=bar,"baz quux"
450 \[\[[^]]*\]\] # Link target
458 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
459 foreach ( $matches as $bits ) {
460 $match = array_shift( $bits );
461 $key = strtolower( array_shift( $bits ) );
462 if ( count( $bits ) == 0 ) {
464 } elseif ( count( $bits ) == 1 ) {
465 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
468 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
475 private function cleanupOption( $opt ) {
476 if ( substr( $opt, 0, 1 ) == '"' ) {
477 return substr( $opt, 1, -1 );
479 if ( substr( $opt, 0, 2 ) == '[[' ) {
480 return substr( $opt, 2, -2 );
486 * Set up the global variables for a consistent environment for each test.
487 * Ideally this should replace the global configuration entirely.
489 private function setupGlobals( $opts = '', $config = '' ) {
492 # Find out values for some special options.
494 self::getOptionValue( 'language', $opts, 'en' );
496 self::getOptionValue( 'variant', $opts, false );
498 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
499 $linkHolderBatchSize =
500 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
503 'wgServer' => 'http://localhost',
504 'wgScript' => '/index.php',
505 'wgScriptPath' => '/',
506 'wgArticlePath' => '/wiki/$1',
507 'wgActionPaths' => array(),
508 'wgLocalFileRepo' => array(
509 'class' => 'LocalRepo',
511 'directory' => $this->uploadDir,
512 'url' => 'http://example.com/images',
514 'transformVia404' => false,
516 'wgEnableUploads' => true,
517 'wgStyleSheetPath' => '/skins',
518 'wgSitename' => 'MediaWiki',
519 'wgServerName' => 'Britney-Spears',
520 'wgLanguageCode' => $lang,
521 'wgContLanguageCode' => $lang,
522 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
523 'wgRawHtml' => isset( $opts['rawhtml'] ),
525 'wgContLang' => null,
526 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
527 'wgMaxTocLevel' => $maxtoclevel,
528 'wgCapitalLinks' => true,
529 'wgNoFollowLinks' => true,
530 'wgNoFollowDomainExceptions' => array(),
531 'wgThumbnailScriptPath' => false,
532 'wgUseImageResize' => false,
533 'wgUseTeX' => isset( $opts['math'] ),
534 'wgMathDirectory' => $this->uploadDir . '/math',
535 'wgLocaltimezone' => 'UTC',
536 'wgAllowExternalImages' => true,
537 'wgUseTidy' => false,
538 'wgDefaultLanguageVariant' => $variant,
539 'wgVariantArticlePath' => false,
540 'wgGroupPermissions' => array( '*' => array(
541 'createaccount' => true,
544 'createpage' => true,
545 'createtalk' => true,
547 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
548 'wgDefaultExternalStore' => array(),
549 'wgForeignFileRepos' => array(),
550 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
551 'wgExperimentalHtmlIds' => false,
552 'wgExternalLinkTarget' => false,
553 'wgAlwaysUseTidy' => false,
555 'wgWellFormedXml' => true,
556 'wgAllowMicrodataAttributes' => true,
560 $configLines = explode( "\n", $config );
562 foreach ( $configLines as $line ) {
563 list( $var, $value ) = explode( '=', $line, 2 );
565 $settings[$var] = eval( "return $value;" );
569 $this->savedGlobals = array();
570 foreach ( $settings as $var => $val ) {
571 if ( array_key_exists( $var, $GLOBALS ) ) {
572 $this->savedGlobals[$var] = $GLOBALS[$var];
574 $GLOBALS[$var] = $val;
576 $langObj = Language::factory( $lang );
577 $GLOBALS['wgLang'] = $langObj;
578 $GLOBALS['wgContLang'] = $langObj;
579 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
580 $GLOBALS['wgOut'] = new OutputPage;
583 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
584 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
585 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
587 MagicWord::clearCache();
590 $wgUser = new User();
594 * List of temporary tables to create, without prefix.
595 * Some of these probably aren't necessary.
597 private function listTables() {
599 $tables = array( 'user', 'page', 'page_restrictions',
600 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
601 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
602 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
603 'recentchanges', 'watchlist', 'math', 'interwiki',
604 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
605 'archive', 'user_groups', 'page_props', 'category',
608 if ( $wgDBtype === 'mysql' )
609 array_push( $tables, 'searchindex' );
611 // Allow extensions to add to the list of tables to duplicate;
612 // may be necessary if they hook into page save or other code
613 // which will require them while running tests.
614 wfRunHooks( 'ParserTestTables', array( &$tables ) );
620 * Set up a temporary set of wiki tables to work with for the tests.
621 * Currently this will only be done once per run, and any changes to
622 * the db will be visible to later tests in the run.
624 public function setupDatabase() {
625 global $wgDBprefix, $wgDBtype;
626 if ( $this->databaseSetupDone ) {
629 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
630 throw new MWException( 'setupDatabase should be called before setupGlobals' );
632 $this->databaseSetupDone = true;
633 $this->oldTablePrefix = $wgDBprefix;
635 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
636 # It seems to have been fixed since (r55079?).
637 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
639 # CREATE TEMPORARY TABLE breaks if there is more than one server
640 if ( wfGetLB()->getServerCount() != 1 ) {
641 $this->useTemporaryTables = false;
644 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
646 $db = wfGetDB( DB_MASTER );
647 $tables = $this->listTables();
649 foreach ( $tables as $tbl ) {
650 # Clean up from previous aborted run. So that table escaping
651 # works correctly across DB engines, we need to change the pre-
652 # fix back and forth so tableName() works right.
653 $this->changePrefix( $this->oldTablePrefix );
654 $oldTableName = $db->tableName( $tbl );
655 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
656 $newTableName = $db->tableName( $tbl );
658 if ( $wgDBtype == 'mysql' ) {
659 $db->query( "DROP TABLE IF EXISTS $newTableName" );
660 } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
661 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
662 * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
663 * syntax would also work for mysql.
665 } elseif ( $db->tableExists( $tbl ) ) {
666 $db->query( "DROP TABLE $newTableName" );
669 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
671 if ( $wgDBtype == 'oracle' )
672 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
674 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
676 # Hack: insert a few Wikipedia in-project interwiki prefixes,
677 # for testing inter-language links
678 $db->insert( 'interwiki', array(
679 array( 'iw_prefix' => 'wikipedia',
680 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
684 array( 'iw_prefix' => 'meatball',
685 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
689 array( 'iw_prefix' => 'zh',
690 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
694 array( 'iw_prefix' => 'es',
695 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
699 array( 'iw_prefix' => 'fr',
700 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
704 array( 'iw_prefix' => 'ru',
705 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
712 if ( $wgDBtype == 'oracle' ) {
713 # Insert 0 user to prevent FK violations
716 $db->insert( 'user', array(
718 'user_name' => 'Anonymous' ) );
721 # Update certain things in site_stats
722 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
724 # Reinitialise the LocalisationCache to match the database state
725 Language::getLocalisationCache()->unloadAll();
727 # Make a new message cache
728 global $wgMessageCache, $wgMemc;
729 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
731 $this->uploadDir = $this->setupUploadDir();
732 $user = User::createNew( 'WikiSysop' );
733 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
734 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
738 'media_type' => MEDIATYPE_BITMAP,
739 'mime' => 'image/jpeg',
740 'metadata' => serialize( array() ),
742 ), $db->timestamp( '20010115123500' ), $user );
744 # This image will be blacklisted in [[MediaWiki:Bad image list]]
745 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
746 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
750 'media_type' => MEDIATYPE_BITMAP,
751 'mime' => 'image/jpeg',
752 'metadata' => serialize( array() ),
754 ), $db->timestamp( '20010115123500' ), $user );
758 * Change the table prefix on all open DB connections/
760 protected function changePrefix( $prefix ) {
762 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
763 $wgDBprefix = $prefix;
766 public function changeLBPrefix( $lb, $prefix ) {
767 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
770 public function changeDBPrefix( $db, $prefix ) {
771 $db->tablePrefix( $prefix );
774 public function teardownDatabase() {
776 if ( !$this->databaseSetupDone ) {
779 $this->teardownUploadDir( $this->uploadDir );
781 $this->changePrefix( $this->oldTablePrefix );
782 $this->databaseSetupDone = false;
783 if ( $this->useTemporaryTables ) {
784 # Don't need to do anything
788 $tables = $this->listTables();
789 $db = wfGetDB( DB_MASTER );
790 foreach ( $tables as $table ) {
791 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
794 if ($wgDBtype == 'oracle')
795 $db->query('BEGIN FILL_WIKI_INFO; END;');
799 * Create a dummy uploads directory which will contain a couple
800 * of files in order to pass existence tests.
802 * @return String: the directory
804 private function setupUploadDir() {
806 if ( $this->keepUploads ) {
807 $dir = wfTempDir() . '/mwParser-images';
808 if ( is_dir( $dir ) ) {
812 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
815 //wfDebug( "Creating upload directory $dir\n" );
816 if ( file_exists( $dir ) ) {
817 wfDebug( "Already exists!\n" );
820 wfMkdirParents( $dir . '/3/3a' );
821 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
822 wfMkdirParents( $dir . '/0/09' );
823 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
828 * Restore default values and perform any necessary clean-up
829 * after each test runs.
831 private function teardownGlobals() {
832 RepoGroup::destroySingleton();
833 LinkCache::singleton()->clear();
834 foreach ( $this->savedGlobals as $var => $val ) {
835 $GLOBALS[$var] = $val;
840 * Remove the dummy uploads directory
842 private function teardownUploadDir( $dir ) {
843 if ( $this->keepUploads ) {
847 // delete the files first, then the dirs.
850 "$dir/3/3a/Foobar.jpg",
851 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
852 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
853 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
854 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
858 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
868 "$dir/thumb/3/3a/Foobar.jpg",
885 * Delete the specified files, if they exist.
886 * @param $files Array: full paths to files to delete.
888 private static function deleteFiles( $files ) {
889 foreach ( $files as $file ) {
890 if ( file_exists( $file ) ) {
897 * Delete the specified directories, if they exist. Must be empty.
898 * @param $dirs Array: full paths to directories to delete.
900 private static function deleteDirs( $dirs ) {
901 foreach ( $dirs as $dir ) {
902 if ( is_dir( $dir ) ) {
909 * "Running test $desc..."
911 protected function showTesting( $desc ) {
912 print "Running test $desc... ";
916 * Print a happy success message.
918 * @param $desc String: the test name
921 protected function showSuccess( $desc ) {
922 if ( $this->showProgress ) {
923 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
929 * Print a failure message and provide some explanatory output
930 * about what went wrong if so configured.
932 * @param $desc String: the test name
933 * @param $result String: expected HTML output
934 * @param $html String: actual HTML output
937 protected function showFailure( $desc, $result, $html ) {
938 if ( $this->showFailure ) {
939 if ( !$this->showProgress ) {
940 # In quiet mode we didn't show the 'Testing' message before the
941 # test, in case it succeeded. Show it now:
942 $this->showTesting( $desc );
944 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
945 if ( $this->showOutput ) {
946 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
948 if ( $this->showDiffs ) {
949 print $this->quickDiff( $result, $html );
950 if ( !$this->wellFormed( $html ) ) {
951 print "XML error: $this->mXmlError\n";
959 * Run given strings through a diff and return the (colorized) output.
960 * Requires writable /tmp directory and a 'diff' command in the PATH.
962 * @param $input String
963 * @param $output String
964 * @param $inFileTail String: tailing for the input file name
965 * @param $outFileTail String: tailing for the output file name
968 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
969 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
971 $infile = "$prefix-$inFileTail";
972 $this->dumpToFile( $input, $infile );
974 $outfile = "$prefix-$outFileTail";
975 $this->dumpToFile( $output, $outfile );
977 $diff = `diff -au $infile $outfile`;
981 return $this->colorDiff( $diff );
985 * Write the given string to a file, adding a final newline.
987 * @param $data String
988 * @param $filename String
990 private function dumpToFile( $data, $filename ) {
991 $file = fopen( $filename, "wt" );
992 fwrite( $file, $data . "\n" );
997 * Colorize unified diff output if set for ANSI color output.
998 * Subtractions are colored blue, additions red.
1000 * @param $text String
1003 protected function colorDiff( $text ) {
1004 return preg_replace(
1005 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1006 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1007 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1012 * Show "Reading tests from ..."
1014 * @param $path String
1016 public function showRunFile( $path ) {
1017 print $this->term->color( 1 ) .
1018 "Reading tests from \"$path\"..." .
1019 $this->term->reset() .
1024 * Insert a temporary test article
1025 * @param $name String: the title, including any prefix
1026 * @param $text String: the article text
1027 * @param $line Integer: the input line number, for reporting errors
1029 public function addArticle( $name, $text, $line ) {
1030 $title = Title::newFromText( $name );
1031 if ( is_null( $title ) ) {
1032 wfDie( "invalid title at line $line\n" );
1035 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1037 wfDie( "duplicate article '$name' at line $line\n" );
1040 $art = new Article( $title );
1041 $art->insertNewArticle( $text, '', false, false );
1045 * Steal a callback function from the primary parser, save it for
1046 * application to our scary parser. If the hook is not installed,
1047 * abort processing of this file.
1049 * @param $name String
1050 * @return Bool true if tag hook is present
1052 public function requireHook( $name ) {
1054 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1055 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1056 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1058 echo " This test suite requires the '$name' hook extension, skipping.\n";
1065 * Steal a callback function from the primary parser, save it for
1066 * application to our scary parser. If the hook is not installed,
1067 * abort processing of this file.
1069 * @param $name String
1070 * @return Bool true if function hook is present
1072 public function requireFunctionHook( $name ) {
1074 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1075 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1076 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1078 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1085 * Run the "tidy" command on text if the $wgUseTidy
1088 * @param $text String: the text to tidy
1092 private function tidy( $text ) {
1095 $text = Parser::tidy( $text );
1100 private function wellFormed( $text ) {
1102 Sanitizer::hackDocType() .
1107 $parser = xml_parser_create( "UTF-8" );
1109 # case folding violates XML standard, turn it off
1110 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1112 if ( !xml_parse( $parser, $html, true ) ) {
1113 $err = xml_error_string( xml_get_error_code( $parser ) );
1114 $position = xml_get_current_byte_index( $parser );
1115 $fragment = $this->extractFragment( $html, $position );
1116 $this->mXmlError = "$err at byte $position:\n$fragment";
1117 xml_parser_free( $parser );
1120 xml_parser_free( $parser );
1124 private function extractFragment( $text, $position ) {
1125 $start = max( 0, $position - 10 );
1126 $before = $position - $start;
1128 $this->term->color( 34 ) .
1129 substr( $text, $start, $before ) .
1130 $this->term->color( 0 ) .
1131 $this->term->color( 31 ) .
1132 $this->term->color( 1 ) .
1133 substr( $text, $position, 1 ) .
1134 $this->term->color( 0 ) .
1135 $this->term->color( 34 ) .
1136 substr( $text, $position + 1, 9 ) .
1137 $this->term->color( 0 ) .
1139 $display = str_replace( "\n", ' ', $fragment );
1141 str_repeat( ' ', $before ) .
1142 $this->term->color( 31 ) .
1144 $this->term->color( 0 );
1145 return "$display\n$caret";
1148 static function getFakeTimestamp( &$parser, &$ts ) {
1154 class AnsiTermColorer {
1155 function __construct() {
1159 * Return ANSI terminal escape code for changing text attribs/color
1161 * @param $color String: semicolon-separated list of attribute/color codes
1164 public function color( $color ) {
1165 global $wgCommandLineDarkBg;
1166 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1167 return "\x1b[{$light}{$color}m";
1171 * Return ANSI terminal escape code for restoring default text attributes
1175 public function reset() {
1176 return $this->color( 0 );
1180 /* A colour-less terminal */
1181 class DummyTermColorer {
1182 public function color( $color ) {
1186 public function reset() {
1191 class TestRecorder {
1195 function __construct( $parent ) {
1196 $this->parent = $parent;
1197 $this->term = $parent->term;
1205 function record( $test, $result ) {
1207 $this->success += ( $result ? 1 : 0 );
1215 if ( $this->total > 0 ) {
1216 $this->reportPercentage( $this->success, $this->total );
1218 wfDie( "No tests found.\n" );
1222 function reportPercentage( $success, $total ) {
1223 $ratio = wfPercent( 100 * $success / $total );
1224 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1225 if ( $success == $total ) {
1226 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1228 $failed = $total - $success ;
1229 print $this->term->color( 31 ) . "$failed tests failed!";
1231 print $this->term->reset() . "\n";
1232 return ( $success == $total );
1236 class DbTestPreviewer extends TestRecorder {
1237 protected $lb; // /< Database load balancer
1238 protected $db; // /< Database connection to the main DB
1239 protected $curRun; // /< run ID number for the current run
1240 protected $prevRun; // /< run ID number for the previous run, if any
1241 protected $results; // /< Result array
1244 * This should be called before the table prefix is changed
1246 function __construct( $parent ) {
1247 parent::__construct( $parent );
1248 $this->lb = wfGetLBFactory()->newMainLB();
1249 // This connection will have the wiki's table prefix, not parsertest_
1250 $this->db = $this->lb->getConnection( DB_MASTER );
1254 * Set up result recording; insert a record for the run with the date
1255 * and all that fun stuff
1260 if ( ! $this->db->tableExists( 'testrun' )
1261 or ! $this->db->tableExists( 'testitem' ) )
1263 print "WARNING> `testrun` table not found in database.\n";
1264 $this->prevRun = false;
1266 // We'll make comparisons against the previous run later...
1267 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1269 $this->results = array();
1272 function record( $test, $result ) {
1273 parent::record( $test, $result );
1274 $this->results[$test] = $result;
1278 if ( $this->prevRun ) {
1279 // f = fail, p = pass, n = nonexistent
1280 // codes show before then after
1282 'fp' => 'previously failing test(s) now PASSING! :)',
1283 'pn' => 'previously PASSING test(s) removed o_O',
1284 'np' => 'new PASSING test(s) :)',
1286 'pf' => 'previously passing test(s) now FAILING! :(',
1287 'fn' => 'previously FAILING test(s) removed O_o',
1288 'nf' => 'new FAILING test(s) :(',
1289 'ff' => 'still FAILING test(s) :(',
1292 $prevResults = array();
1294 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1295 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1296 foreach ( $res as $row ) {
1297 if ( !$this->parent->regex
1298 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1300 $prevResults[$row->ti_name] = $row->ti_success;
1304 $combined = array_keys( $this->results + $prevResults );
1306 # Determine breakdown by change type
1307 $breakdown = array();
1308 foreach ( $combined as $test ) {
1309 if ( !isset( $prevResults[$test] ) ) {
1311 } elseif ( $prevResults[$test] == 1 ) {
1313 } else /* if ( $prevResults[$test] == 0 )*/ {
1316 if ( !isset( $this->results[$test] ) ) {
1318 } elseif ( $this->results[$test] == 1 ) {
1320 } else /*if ( $this->results[$test] == 0 ) */ {
1323 $code = $before . $after;
1324 if ( isset( $table[$code] ) ) {
1325 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1330 foreach ( $table as $code => $label ) {
1331 if ( !empty( $breakdown[$code] ) ) {
1332 $count = count( $breakdown[$code] );
1333 printf( "\n%4d %s\n", $count, $label );
1334 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1335 print " * $differing_test_name [$statusInfo]\n";
1340 print "No previous test runs to compare against.\n";
1347 ** Returns a string giving information about when a test last had a status change.
1348 ** Could help to track down when regressions were introduced, as distinct from tests
1349 ** which have never passed (which are more change requests than regressions).
1351 private function getTestStatusInfo( $testname, $after ) {
1353 // If we're looking at a test that has just been removed, then say when it first appeared.
1354 if ( $after == 'n' ) {
1355 $changedRun = $this->db->selectField ( 'testitem',
1357 array( 'ti_name' => $testname ),
1359 $appear = $this->db->selectRow ( 'testrun',
1360 array( 'tr_date', 'tr_mw_version' ),
1361 array( 'tr_id' => $changedRun ),
1363 return "First recorded appearance: "
1364 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1365 . ", " . $appear->tr_mw_version;
1368 // Otherwise, this test has previous recorded results.
1369 // See when this test last had a different result to what we're seeing now.
1371 'ti_name' => $testname,
1372 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1373 if ( $this->curRun ) {
1374 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1377 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1379 // If no record of ever having had a different result.
1380 if ( is_null ( $changedRun ) ) {
1381 if ( $after == "f" ) {
1382 return "Has never passed";
1384 return "Has never failed";
1388 // Otherwise, we're looking at a test whose status has changed.
1389 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1390 // In this situation, give as much info as we can as to when it changed status.
1391 $pre = $this->db->selectRow ( 'testrun',
1392 array( 'tr_date', 'tr_mw_version' ),
1393 array( 'tr_id' => $changedRun ),
1395 $post = $this->db->selectRow ( 'testrun',
1396 array( 'tr_date', 'tr_mw_version' ),
1397 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1399 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1403 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1407 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1408 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1414 * Commit transaction and clean up for result recording
1417 $this->lb->commitMasterChanges();
1418 $this->lb->closeAll();
1424 class DbTestRecorder extends DbTestPreviewer {
1428 * Set up result recording; insert a record for the run with the date
1429 * and all that fun stuff
1435 if ( ! $this->db->tableExists( 'testrun' )
1436 or ! $this->db->tableExists( 'testitem' ) )
1438 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1439 if ( $wgDBtype === 'postgres' )
1440 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1441 elseif ( $wgDBtype === 'oracle' )
1442 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1444 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1445 echo "OK, resuming.\n";
1450 $this->db->insert( 'testrun',
1452 'tr_date' => $this->db->timestamp(),
1453 'tr_mw_version' => $this->version,
1454 'tr_php_version' => phpversion(),
1455 'tr_db_version' => $this->db->getServerVersion(),
1456 'tr_uname' => php_uname()
1459 if ( $wgDBtype === 'postgres' )
1460 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1462 $this->curRun = $this->db->insertId();
1466 * Record an individual test item's success or failure to the db
1468 * @param $test String
1469 * @param $result Boolean
1471 function record( $test, $result ) {
1472 parent::record( $test, $result );
1473 $this->db->insert( 'testitem',
1475 'ti_run' => $this->curRun,
1477 'ti_success' => $result ? 1 : 0,
1483 class RemoteTestRecorder extends TestRecorder {
1486 $this->results = array();
1487 $this->ping( 'running' );
1490 function record( $test, $result ) {
1491 parent::record( $test, $result );
1492 $this->results[$test] = (bool)$result;
1496 $this->ping( 'complete', $this->results );
1501 * Inform a CodeReview instance that we've started or completed a test run...
1503 * @param $status string: "running" - tell it we've started
1504 * "complete" - provide test results array
1505 * "abort" - something went horribly awry
1506 * @param $results array of test name => true/false
1508 function ping( $status, $results = false ) {
1509 global $wgParserTestRemote, $IP;
1511 $remote = $wgParserTestRemote;
1512 $revId = SpecialVersion::getSvnRevision( $IP );
1513 $jsonResults = FormatJson::encode( $results );
1516 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1520 // Generate a hash MAC to validate our credentials
1527 if ( $status == "complete" ) {
1528 $message[] = $jsonResults;
1530 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1533 'action' => 'codetestupload',
1535 'repo' => $remote['repo'],
1536 'suite' => $remote['suite'],
1538 'status' => $status,
1541 if ( $status == "complete" ) {
1542 $postData['results'] = $jsonResults;
1544 $response = $this->post( $remote['api-url'], $postData );
1546 if ( $response === false ) {
1547 print "CodeReview info upload failed to reach server.\n";
1550 $responseData = FormatJson::decode( $response, true );
1551 if ( !is_array( $responseData ) ) {
1552 print "CodeReview API response not recognized...\n";
1553 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1556 if ( isset( $responseData['error'] ) ) {
1557 $code = $responseData['error']['code'];
1558 $info = $responseData['error']['info'];
1559 print "CodeReview info upload failed: $code $info\n";
1564 function post( $url, $data ) {
1565 return Http::post( $url, array( 'postData' => $data ) );
1569 class TestFileIterator implements Iterator {
1578 function __construct( $file, $parser = null ) {
1581 $this->file = $file;
1582 $this->fh = fopen( $this->file, "rt" );
1584 wfDie( "Couldn't open file '$file'\n" );
1587 $this->parser = $parser;
1589 if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1590 $this->lineNum = $this->index = 0;
1593 function setParser( ParserTest $parser ) {
1594 $this->parser = $parser;
1598 if ( fseek( $this->fh, 0 ) ) {
1599 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1609 function current() {
1614 return $this->index;
1618 if ( $this->readNextTest() ) {
1627 return $this->eof != true;
1630 function readNextTest() {
1634 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1637 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1638 $section = strtolower( $matches[1] );
1639 if ( $section == 'endarticle' ) {
1640 if ( !isset( $data['text'] ) ) {
1641 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1643 if ( !isset( $data['article'] ) ) {
1644 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1646 if ( $this->parser ) {
1647 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1654 if ( $section == 'endhooks' ) {
1655 if ( !isset( $data['hooks'] ) ) {
1656 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1658 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1659 $line = trim( $line );
1661 if ( $this->parser && !$this->parser->requireHook( $line ) ) {
1670 if ( $section == 'endfunctionhooks' ) {
1671 if ( !isset( $data['functionhooks'] ) ) {
1672 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1674 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1675 $line = trim( $line );
1677 if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
1686 if ( $section == 'end' ) {
1687 if ( !isset( $data['test'] ) ) {
1688 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1690 if ( !isset( $data['input'] ) ) {
1691 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1693 if ( !isset( $data['result'] ) ) {
1694 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1696 if ( !isset( $data['options'] ) ) {
1697 $data['options'] = '';
1699 if ( !isset( $data['config'] ) )
1700 $data['config'] = '';
1703 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1704 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
1711 if ( $this->parser &&
1712 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$wgUseTeX ) {
1713 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1719 if ( $this->parser ) {
1720 $this->test = array(
1721 'test' => $this->parser->chomp( $data['test'] ),
1722 'input' => $this->parser->chomp( $data['input'] ),
1723 'result' => $this->parser->chomp( $data['result'] ),
1724 'options' => $this->parser->chomp( $data['options'] ),
1725 'config' => $this->parser->chomp( $data['config'] ) );
1727 $this->test['test'] = $data['test'];
1731 if ( isset ( $data[$section] ) ) {
1732 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1734 $data[$section] = '';
1738 $data[$section] .= $line;