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 $dict = $this->getFuzzInput( $filenames );
149 $dictSize = strlen( $dict );
150 $logMaxLength = log( $this->maxFuzzTestLength );
151 $this->setupDatabase();
152 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
157 $opts = ParserOptions::newFromUser( $user );
158 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
161 // Generate test input
162 mt_srand( ++$this->fuzzSeed );
163 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
165 while ( strlen( $input ) < $totalLength ) {
166 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
167 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
168 $offset = mt_rand( 0, $dictSize - $hairLength );
169 $input .= substr( $dict, $offset, $hairLength );
172 $this->setupGlobals();
173 $parser = $this->getParser();
176 $parser->parse( $input, $title, $opts );
178 } catch ( Exception $exception ) {
183 echo "Test failed with seed {$this->fuzzSeed}\n";
192 $this->teardownGlobals();
193 $parser->__destruct();
195 if ( $numTotal % 100 == 0 ) {
196 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
197 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
199 echo "Out of memory:\n";
200 $memStats = $this->getMemoryBreakdown();
201 foreach ( $memStats as $name => $usage ) {
202 echo "$name: $usage\n";
211 * Get an input dictionary from a set of parser test files
213 function getFuzzInput( $filenames ) {
215 foreach ( $filenames as $filename ) {
216 $contents = file_get_contents( $filename );
217 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
218 foreach ( $matches[1] as $match ) {
219 $dict .= $match . "\n";
226 * Get a memory usage breakdown
228 function getMemoryBreakdown() {
230 foreach ( $GLOBALS as $name => $value ) {
231 $memStats['$' . $name] = strlen( serialize( $value ) );
233 $classes = get_declared_classes();
234 foreach ( $classes as $class ) {
235 $rc = new ReflectionClass( $class );
236 $props = $rc->getStaticProperties();
237 $memStats[$class] = strlen( serialize( $props ) );
238 $methods = $rc->getMethods();
239 foreach ( $methods as $method ) {
240 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
243 $functions = get_defined_functions();
244 foreach ( $functions['user'] as $function ) {
245 $rf = new ReflectionFunction( $function );
246 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
257 * Run a series of tests listed in the given text files.
258 * Each test consists of a brief description, wikitext input,
259 * and the expected HTML output.
261 * Prints status updates on stdout and counts up the total
262 * number and percentage of passed tests.
264 * @param $filenames Array of strings
265 * @return Boolean: true if passed all tests, false if any tests failed.
267 public function runTestsFromFiles( $filenames ) {
268 $this->recorder->start();
269 $this->setupDatabase();
271 foreach ( $filenames as $filename ) {
272 $tests = new TestFileIterator( $filename, $this );
273 $ok = $this->runTests( $tests ) && $ok;
275 $this->teardownDatabase();
276 $this->recorder->report();
277 $this->recorder->end();
281 function runTests( $tests ) {
283 foreach ( $tests as $i => $t ) {
285 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
286 $ok = $ok && $result;
287 $this->recorder->record( $t['test'], $result );
289 if ( $this->showProgress ) {
296 * Get a Parser object
298 function getParser( $preprocessor = null ) {
299 global $wgParserConf;
300 $class = $wgParserConf['class'];
301 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
302 foreach ( $this->hooks as $tag => $callback ) {
303 $parser->setHook( $tag, $callback );
305 foreach ( $this->functionHooks as $tag => $bits ) {
306 list( $callback, $flags ) = $bits;
307 $parser->setFunctionHook( $tag, $callback, $flags );
309 wfRunHooks( 'ParserTestParser', array( &$parser ) );
314 * Run a given wikitext input through a freshly-constructed wiki parser,
315 * and compare the output against the expected results.
316 * Prints status and explanatory messages to stdout.
318 * @param $desc String: test's description
319 * @param $input String: wikitext to try rendering
320 * @param $result String: result to output
321 * @param $opts Array: test's options
322 * @param $config String: overrides for global variables, one per line
325 public function runTest( $desc, $input, $result, $opts, $config ) {
326 if ( $this->showProgress ) {
327 $this->showTesting( $desc );
330 $opts = $this->parseOptions( $opts );
331 $this->setupGlobals( $opts, $config );
334 $options = ParserOptions::newFromUser( $user );
337 if ( isset( $opts['title'] ) ) {
338 $titleText = $opts['title'];
341 $titleText = 'Parser test';
344 $noxml = isset( $opts['noxml'] );
345 $local = isset( $opts['local'] );
346 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
347 $parser = $this->getParser( $preprocessor );
348 $title = Title::newFromText( $titleText );
351 if ( isset( $opts['pst'] ) ) {
352 $out = $parser->preSaveTransform( $input, $title, $user, $options );
353 } elseif ( isset( $opts['msg'] ) ) {
354 $out = $parser->transformMsg( $input, $options );
355 } elseif ( isset( $opts['section'] ) ) {
356 $section = $opts['section'];
357 $out = $parser->getSection( $input, $section );
358 } elseif ( isset( $opts['replace'] ) ) {
359 $section = $opts['replace'][0];
360 $replace = $opts['replace'][1];
361 $out = $parser->replaceSection( $input, $section, $replace );
362 } elseif ( isset( $opts['comment'] ) ) {
363 $linker = $user->getSkin();
364 $out = $linker->formatComment( $input, $title, $local );
365 } elseif ( isset( $opts['preload'] ) ) {
366 $out = $parser->getpreloadText( $input, $title, $options );
368 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
369 $out = $output->getText();
371 if ( isset( $opts['showtitle'] ) ) {
372 if ( $output->getTitleText() ) $title = $output->getTitleText();
373 $out = "$title\n$out";
375 if ( isset( $opts['ill'] ) ) {
376 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
377 } elseif ( isset( $opts['cat'] ) ) {
379 $wgOut->addCategoryLinks( $output->getCategories() );
380 $cats = $wgOut->getCategoryLinks();
381 if ( isset( $cats['normal'] ) ) {
382 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
388 $result = $this->tidy( $result );
392 $this->teardownGlobals();
394 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
395 return $this->showSuccess( $desc );
397 return $this->showFailure( $desc, $result, $out );
403 * Use a regex to find out the value of an option
404 * @param $key String: name of option val to retrieve
405 * @param $opts Options array to look in
406 * @param $default Mixed: default value returned if not found
408 private static function getOptionValue( $key, $opts, $default ) {
409 $key = strtolower( $key );
410 if ( isset( $opts[$key] ) ) {
417 private function parseOptions( $instring ) {
419 $lines = explode( "\n", $instring );
424 // foo=bar,"baz quux"
448 \[\[[^]]*\]\] # Link target
456 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
457 foreach ( $matches as $bits ) {
458 $match = array_shift( $bits );
459 $key = strtolower( array_shift( $bits ) );
460 if ( count( $bits ) == 0 ) {
462 } elseif ( count( $bits ) == 1 ) {
463 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
466 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
473 private function cleanupOption( $opt ) {
474 if ( substr( $opt, 0, 1 ) == '"' ) {
475 return substr( $opt, 1, -1 );
477 if ( substr( $opt, 0, 2 ) == '[[' ) {
478 return substr( $opt, 2, -2 );
484 * Set up the global variables for a consistent environment for each test.
485 * Ideally this should replace the global configuration entirely.
487 private function setupGlobals( $opts = '', $config = '' ) {
489 if ( !isset( $this->uploadDir ) ) {
490 $this->uploadDir = $this->setupUploadDir();
493 # Find out values for some special options.
495 self::getOptionValue( 'language', $opts, 'en' );
497 self::getOptionValue( 'variant', $opts, false );
499 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
500 $linkHolderBatchSize =
501 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
504 'wgServer' => 'http://localhost',
505 'wgScript' => '/index.php',
506 'wgScriptPath' => '/',
507 'wgArticlePath' => '/wiki/$1',
508 'wgActionPaths' => array(),
509 'wgLocalFileRepo' => array(
510 'class' => 'LocalRepo',
512 'directory' => $this->uploadDir,
513 'url' => 'http://example.com/images',
515 'transformVia404' => false,
517 'wgEnableUploads' => true,
518 'wgStyleSheetPath' => '/skins',
519 'wgSitename' => 'MediaWiki',
520 'wgServerName' => 'Britney-Spears',
521 'wgLanguageCode' => $lang,
522 'wgContLanguageCode' => $lang,
523 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
524 'wgRawHtml' => isset( $opts['rawhtml'] ),
526 'wgContLang' => null,
527 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
528 'wgMaxTocLevel' => $maxtoclevel,
529 'wgCapitalLinks' => true,
530 'wgNoFollowLinks' => true,
531 'wgNoFollowDomainExceptions' => array(),
532 'wgThumbnailScriptPath' => false,
533 'wgUseImageResize' => false,
534 'wgUseTeX' => isset( $opts['math'] ),
535 'wgMathDirectory' => $this->uploadDir . '/math',
536 'wgLocaltimezone' => 'UTC',
537 'wgAllowExternalImages' => true,
538 'wgUseTidy' => false,
539 'wgDefaultLanguageVariant' => $variant,
540 'wgVariantArticlePath' => false,
541 'wgGroupPermissions' => array( '*' => array(
542 'createaccount' => true,
545 'createpage' => true,
546 'createtalk' => true,
548 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
549 'wgDefaultExternalStore' => array(),
550 'wgForeignFileRepos' => array(),
551 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
552 'wgExperimentalHtmlIds' => false,
553 'wgExternalLinkTarget' => false,
554 'wgAlwaysUseTidy' => false,
556 'wgWellFormedXml' => true,
557 'wgAllowMicrodataAttributes' => true,
561 $configLines = explode( "\n", $config );
563 foreach ( $configLines as $line ) {
564 list( $var, $value ) = explode( '=', $line, 2 );
566 $settings[$var] = eval( "return $value;" );
570 $this->savedGlobals = array();
571 foreach ( $settings as $var => $val ) {
572 if ( array_key_exists( $var, $GLOBALS ) ) {
573 $this->savedGlobals[$var] = $GLOBALS[$var];
575 $GLOBALS[$var] = $val;
577 $langObj = Language::factory( $lang );
578 $GLOBALS['wgLang'] = $langObj;
579 $GLOBALS['wgContLang'] = $langObj;
580 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
581 $GLOBALS['wgOut'] = new OutputPage;
584 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
585 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
586 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
588 MagicWord::clearCache();
591 $wgUser = new User();
595 * List of temporary tables to create, without prefix.
596 * Some of these probably aren't necessary.
598 private function listTables() {
600 $tables = array( 'user', 'page', 'page_restrictions',
601 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
602 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
603 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
604 'recentchanges', 'watchlist', 'math', 'interwiki',
605 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
606 'archive', 'user_groups', 'page_props', 'category',
609 if ( $wgDBtype === 'mysql' )
610 array_push( $tables, 'searchindex' );
612 // Allow extensions to add to the list of tables to duplicate;
613 // may be necessary if they hook into page save or other code
614 // which will require them while running tests.
615 wfRunHooks( 'ParserTestTables', array( &$tables ) );
621 * Set up a temporary set of wiki tables to work with for the tests.
622 * Currently this will only be done once per run, and any changes to
623 * the db will be visible to later tests in the run.
625 public function setupDatabase() {
626 global $wgDBprefix, $wgDBtype;
627 if ( $this->databaseSetupDone ) {
630 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
631 throw new MWException( 'setupDatabase should be called before setupGlobals' );
633 $this->databaseSetupDone = true;
634 $this->oldTablePrefix = $wgDBprefix;
636 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
637 # It seems to have been fixed since (r55079?).
638 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
640 # CREATE TEMPORARY TABLE breaks if there is more than one server
641 if ( wfGetLB()->getServerCount() != 1 ) {
642 $this->useTemporaryTables = false;
645 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
647 $db = wfGetDB( DB_MASTER );
648 $tables = $this->listTables();
650 foreach ( $tables as $tbl ) {
651 # Clean up from previous aborted run. So that table escaping
652 # works correctly across DB engines, we need to change the pre-
653 # fix back and forth so tableName() works right.
654 $this->changePrefix( $this->oldTablePrefix );
655 $oldTableName = $db->tableName( $tbl );
656 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
657 $newTableName = $db->tableName( $tbl );
659 if ( $wgDBtype == 'mysql' ) {
660 $db->query( "DROP TABLE IF EXISTS $newTableName" );
661 } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
662 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
663 * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
664 * syntax would also work for mysql.
666 } elseif ( $db->tableExists( $tbl ) ) {
667 $db->query( "DROP TABLE $newTableName" );
670 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
672 if ( $wgDBtype == 'oracle' )
673 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
675 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
677 # Hack: insert a few Wikipedia in-project interwiki prefixes,
678 # for testing inter-language links
679 $db->insert( 'interwiki', array(
680 array( 'iw_prefix' => 'wikipedia',
681 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
685 array( 'iw_prefix' => 'meatball',
686 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
690 array( 'iw_prefix' => 'zh',
691 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
695 array( 'iw_prefix' => 'es',
696 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
700 array( 'iw_prefix' => 'fr',
701 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
705 array( 'iw_prefix' => 'ru',
706 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
713 if ( $wgDBtype == 'oracle' ) {
714 # Insert 0 and 1 user_ids to prevent FK violations
717 $db->insert( 'user', array(
719 'user_name' => 'Anonymous' ) );
721 # Hack-on-Hack: Insert a test user to be able to insert an image
722 $db->insert( 'user', array(
724 'user_name' => 'Tester' ) );
727 # Hack: Insert an image to work with
728 $db->insert( 'image', array(
729 'img_name' => 'Foobar.jpg',
731 'img_description' => 'Some lame file',
733 'img_user_text' => 'WikiSysop',
734 'img_timestamp' => $db->timestamp( '20010115123500' ),
738 'img_media_type' => MEDIATYPE_BITMAP,
739 'img_major_mime' => "image",
740 'img_minor_mime' => "jpeg",
741 'img_metadata' => serialize( array() ),
744 # This image will be blacklisted in [[MediaWiki:Bad image list]]
745 $db->insert( 'image', array(
746 'img_name' => 'Bad.jpg',
748 'img_description' => 'zomgnotcensored',
750 'img_user_text' => 'WikiSysop',
751 'img_timestamp' => $db->timestamp( '20010115123500' ),
755 'img_media_type' => MEDIATYPE_BITMAP,
756 'img_major_mime' => "image",
757 'img_minor_mime' => "jpeg",
758 'img_metadata' => serialize( array() ),
761 # Update certain things in site_stats
762 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
764 # Reinitialise the LocalisationCache to match the database state
765 Language::getLocalisationCache()->unloadAll();
767 # Make a new message cache
768 global $wgMessageCache, $wgMemc;
769 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
773 * Change the table prefix on all open DB connections/
775 protected function changePrefix( $prefix ) {
777 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
778 $wgDBprefix = $prefix;
781 public function changeLBPrefix( $lb, $prefix ) {
782 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
785 public function changeDBPrefix( $db, $prefix ) {
786 $db->tablePrefix( $prefix );
789 public function teardownDatabase() {
791 if ( !$this->databaseSetupDone ) {
794 $this->changePrefix( $this->oldTablePrefix );
795 $this->databaseSetupDone = false;
796 if ( $this->useTemporaryTables ) {
797 # Don't need to do anything
801 $tables = $this->listTables();
802 $db = wfGetDB( DB_MASTER );
803 foreach ( $tables as $table ) {
804 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
807 if ($wgDBtype == 'oracle')
808 $db->query('BEGIN FILL_WIKI_INFO; END;');
812 * Create a dummy uploads directory which will contain a couple
813 * of files in order to pass existence tests.
815 * @return String: the directory
817 private function setupUploadDir() {
819 if ( $this->keepUploads ) {
820 $dir = wfTempDir() . '/mwParser-images';
821 if ( is_dir( $dir ) ) {
825 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
828 wfDebug( "Creating upload directory $dir\n" );
829 if ( file_exists( $dir ) ) {
830 wfDebug( "Already exists!\n" );
833 wfMkdirParents( $dir . '/3/3a' );
834 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
836 wfMkdirParents( $dir . '/0/09' );
837 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
842 * Restore default values and perform any necessary clean-up
843 * after each test runs.
845 private function teardownGlobals() {
846 RepoGroup::destroySingleton();
847 LinkCache::singleton()->clear();
848 foreach ( $this->savedGlobals as $var => $val ) {
849 $GLOBALS[$var] = $val;
851 if ( isset( $this->uploadDir ) ) {
852 $this->teardownUploadDir( $this->uploadDir );
853 unset( $this->uploadDir );
858 * Remove the dummy uploads directory
860 private function teardownUploadDir( $dir ) {
861 if ( $this->keepUploads ) {
865 // delete the files first, then the dirs.
868 "$dir/3/3a/Foobar.jpg",
869 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
870 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
871 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
872 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
876 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
886 "$dir/thumb/3/3a/Foobar.jpg",
903 * Delete the specified files, if they exist.
904 * @param $files Array: full paths to files to delete.
906 private static function deleteFiles( $files ) {
907 foreach ( $files as $file ) {
908 if ( file_exists( $file ) ) {
915 * Delete the specified directories, if they exist. Must be empty.
916 * @param $dirs Array: full paths to directories to delete.
918 private static function deleteDirs( $dirs ) {
919 foreach ( $dirs as $dir ) {
920 if ( is_dir( $dir ) ) {
927 * "Running test $desc..."
929 protected function showTesting( $desc ) {
930 print "Running test $desc... ";
934 * Print a happy success message.
936 * @param $desc String: the test name
939 protected function showSuccess( $desc ) {
940 if ( $this->showProgress ) {
941 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
947 * Print a failure message and provide some explanatory output
948 * about what went wrong if so configured.
950 * @param $desc String: the test name
951 * @param $result String: expected HTML output
952 * @param $html String: actual HTML output
955 protected function showFailure( $desc, $result, $html ) {
956 if ( $this->showFailure ) {
957 if ( !$this->showProgress ) {
958 # In quiet mode we didn't show the 'Testing' message before the
959 # test, in case it succeeded. Show it now:
960 $this->showTesting( $desc );
962 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
963 if ( $this->showOutput ) {
964 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
966 if ( $this->showDiffs ) {
967 print $this->quickDiff( $result, $html );
968 if ( !$this->wellFormed( $html ) ) {
969 print "XML error: $this->mXmlError\n";
977 * Run given strings through a diff and return the (colorized) output.
978 * Requires writable /tmp directory and a 'diff' command in the PATH.
980 * @param $input String
981 * @param $output String
982 * @param $inFileTail String: tailing for the input file name
983 * @param $outFileTail String: tailing for the output file name
986 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
987 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
989 $infile = "$prefix-$inFileTail";
990 $this->dumpToFile( $input, $infile );
992 $outfile = "$prefix-$outFileTail";
993 $this->dumpToFile( $output, $outfile );
995 $diff = `diff -au $infile $outfile`;
999 return $this->colorDiff( $diff );
1003 * Write the given string to a file, adding a final newline.
1005 * @param $data String
1006 * @param $filename String
1008 private function dumpToFile( $data, $filename ) {
1009 $file = fopen( $filename, "wt" );
1010 fwrite( $file, $data . "\n" );
1015 * Colorize unified diff output if set for ANSI color output.
1016 * Subtractions are colored blue, additions red.
1018 * @param $text String
1021 protected function colorDiff( $text ) {
1022 return preg_replace(
1023 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1024 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1025 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1030 * Show "Reading tests from ..."
1032 * @param $path String
1034 public function showRunFile( $path ) {
1035 print $this->term->color( 1 ) .
1036 "Reading tests from \"$path\"..." .
1037 $this->term->reset() .
1042 * Insert a temporary test article
1043 * @param $name String: the title, including any prefix
1044 * @param $text String: the article text
1045 * @param $line Integer: the input line number, for reporting errors
1047 public function addArticle( $name, $text, $line ) {
1048 $this->setupGlobals();
1049 $title = Title::newFromText( $name );
1050 if ( is_null( $title ) ) {
1051 wfDie( "invalid title at line $line\n" );
1054 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1056 wfDie( "duplicate article '$name' at line $line\n" );
1059 $art = new Article( $title );
1060 $art->insertNewArticle( $text, '', false, false );
1062 $this->teardownGlobals();
1066 * Steal a callback function from the primary parser, save it for
1067 * application to our scary parser. If the hook is not installed,
1068 * abort processing of this file.
1070 * @param $name String
1071 * @return Bool true if tag hook is present
1073 public function requireHook( $name ) {
1075 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1076 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1077 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1079 echo " This test suite requires the '$name' hook extension, skipping.\n";
1086 * Steal a callback function from the primary parser, save it for
1087 * application to our scary parser. If the hook is not installed,
1088 * abort processing of this file.
1090 * @param $name String
1091 * @return Bool true if function hook is present
1093 public function requireFunctionHook( $name ) {
1095 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1096 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1097 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1099 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1106 * Run the "tidy" command on text if the $wgUseTidy
1109 * @param $text String: the text to tidy
1113 private function tidy( $text ) {
1116 $text = Parser::tidy( $text );
1121 private function wellFormed( $text ) {
1123 Sanitizer::hackDocType() .
1128 $parser = xml_parser_create( "UTF-8" );
1130 # case folding violates XML standard, turn it off
1131 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1133 if ( !xml_parse( $parser, $html, true ) ) {
1134 $err = xml_error_string( xml_get_error_code( $parser ) );
1135 $position = xml_get_current_byte_index( $parser );
1136 $fragment = $this->extractFragment( $html, $position );
1137 $this->mXmlError = "$err at byte $position:\n$fragment";
1138 xml_parser_free( $parser );
1141 xml_parser_free( $parser );
1145 private function extractFragment( $text, $position ) {
1146 $start = max( 0, $position - 10 );
1147 $before = $position - $start;
1149 $this->term->color( 34 ) .
1150 substr( $text, $start, $before ) .
1151 $this->term->color( 0 ) .
1152 $this->term->color( 31 ) .
1153 $this->term->color( 1 ) .
1154 substr( $text, $position, 1 ) .
1155 $this->term->color( 0 ) .
1156 $this->term->color( 34 ) .
1157 substr( $text, $position + 1, 9 ) .
1158 $this->term->color( 0 ) .
1160 $display = str_replace( "\n", ' ', $fragment );
1162 str_repeat( ' ', $before ) .
1163 $this->term->color( 31 ) .
1165 $this->term->color( 0 );
1166 return "$display\n$caret";
1169 static function getFakeTimestamp( &$parser, &$ts ) {
1175 class AnsiTermColorer {
1176 function __construct() {
1180 * Return ANSI terminal escape code for changing text attribs/color
1182 * @param $color String: semicolon-separated list of attribute/color codes
1185 public function color( $color ) {
1186 global $wgCommandLineDarkBg;
1187 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1188 return "\x1b[{$light}{$color}m";
1192 * Return ANSI terminal escape code for restoring default text attributes
1196 public function reset() {
1197 return $this->color( 0 );
1201 /* A colour-less terminal */
1202 class DummyTermColorer {
1203 public function color( $color ) {
1207 public function reset() {
1212 class TestRecorder {
1216 function __construct( $parent ) {
1217 $this->parent = $parent;
1218 $this->term = $parent->term;
1226 function record( $test, $result ) {
1228 $this->success += ( $result ? 1 : 0 );
1236 if ( $this->total > 0 ) {
1237 $this->reportPercentage( $this->success, $this->total );
1239 wfDie( "No tests found.\n" );
1243 function reportPercentage( $success, $total ) {
1244 $ratio = wfPercent( 100 * $success / $total );
1245 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1246 if ( $success == $total ) {
1247 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1249 $failed = $total - $success ;
1250 print $this->term->color( 31 ) . "$failed tests failed!";
1252 print $this->term->reset() . "\n";
1253 return ( $success == $total );
1257 class DbTestPreviewer extends TestRecorder {
1258 protected $lb; // /< Database load balancer
1259 protected $db; // /< Database connection to the main DB
1260 protected $curRun; // /< run ID number for the current run
1261 protected $prevRun; // /< run ID number for the previous run, if any
1262 protected $results; // /< Result array
1265 * This should be called before the table prefix is changed
1267 function __construct( $parent ) {
1268 parent::__construct( $parent );
1269 $this->lb = wfGetLBFactory()->newMainLB();
1270 // This connection will have the wiki's table prefix, not parsertest_
1271 $this->db = $this->lb->getConnection( DB_MASTER );
1275 * Set up result recording; insert a record for the run with the date
1276 * and all that fun stuff
1281 if ( ! $this->db->tableExists( 'testrun' )
1282 or ! $this->db->tableExists( 'testitem' ) )
1284 print "WARNING> `testrun` table not found in database.\n";
1285 $this->prevRun = false;
1287 // We'll make comparisons against the previous run later...
1288 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1290 $this->results = array();
1293 function record( $test, $result ) {
1294 parent::record( $test, $result );
1295 $this->results[$test] = $result;
1299 if ( $this->prevRun ) {
1300 // f = fail, p = pass, n = nonexistent
1301 // codes show before then after
1303 'fp' => 'previously failing test(s) now PASSING! :)',
1304 'pn' => 'previously PASSING test(s) removed o_O',
1305 'np' => 'new PASSING test(s) :)',
1307 'pf' => 'previously passing test(s) now FAILING! :(',
1308 'fn' => 'previously FAILING test(s) removed O_o',
1309 'nf' => 'new FAILING test(s) :(',
1310 'ff' => 'still FAILING test(s) :(',
1313 $prevResults = array();
1315 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1316 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1317 foreach ( $res as $row ) {
1318 if ( !$this->parent->regex
1319 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1321 $prevResults[$row->ti_name] = $row->ti_success;
1325 $combined = array_keys( $this->results + $prevResults );
1327 # Determine breakdown by change type
1328 $breakdown = array();
1329 foreach ( $combined as $test ) {
1330 if ( !isset( $prevResults[$test] ) ) {
1332 } elseif ( $prevResults[$test] == 1 ) {
1334 } else /* if ( $prevResults[$test] == 0 )*/ {
1337 if ( !isset( $this->results[$test] ) ) {
1339 } elseif ( $this->results[$test] == 1 ) {
1341 } else /*if ( $this->results[$test] == 0 ) */ {
1344 $code = $before . $after;
1345 if ( isset( $table[$code] ) ) {
1346 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1351 foreach ( $table as $code => $label ) {
1352 if ( !empty( $breakdown[$code] ) ) {
1353 $count = count( $breakdown[$code] );
1354 printf( "\n%4d %s\n", $count, $label );
1355 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1356 print " * $differing_test_name [$statusInfo]\n";
1361 print "No previous test runs to compare against.\n";
1368 ** Returns a string giving information about when a test last had a status change.
1369 ** Could help to track down when regressions were introduced, as distinct from tests
1370 ** which have never passed (which are more change requests than regressions).
1372 private function getTestStatusInfo( $testname, $after ) {
1374 // If we're looking at a test that has just been removed, then say when it first appeared.
1375 if ( $after == 'n' ) {
1376 $changedRun = $this->db->selectField ( 'testitem',
1378 array( 'ti_name' => $testname ),
1380 $appear = $this->db->selectRow ( 'testrun',
1381 array( 'tr_date', 'tr_mw_version' ),
1382 array( 'tr_id' => $changedRun ),
1384 return "First recorded appearance: "
1385 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1386 . ", " . $appear->tr_mw_version;
1389 // Otherwise, this test has previous recorded results.
1390 // See when this test last had a different result to what we're seeing now.
1392 'ti_name' => $testname,
1393 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1394 if ( $this->curRun ) {
1395 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1398 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1400 // If no record of ever having had a different result.
1401 if ( is_null ( $changedRun ) ) {
1402 if ( $after == "f" ) {
1403 return "Has never passed";
1405 return "Has never failed";
1409 // Otherwise, we're looking at a test whose status has changed.
1410 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1411 // In this situation, give as much info as we can as to when it changed status.
1412 $pre = $this->db->selectRow ( 'testrun',
1413 array( 'tr_date', 'tr_mw_version' ),
1414 array( 'tr_id' => $changedRun ),
1416 $post = $this->db->selectRow ( 'testrun',
1417 array( 'tr_date', 'tr_mw_version' ),
1418 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1420 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1424 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1428 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1429 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1435 * Commit transaction and clean up for result recording
1438 $this->lb->commitMasterChanges();
1439 $this->lb->closeAll();
1445 class DbTestRecorder extends DbTestPreviewer {
1449 * Set up result recording; insert a record for the run with the date
1450 * and all that fun stuff
1456 if ( ! $this->db->tableExists( 'testrun' )
1457 or ! $this->db->tableExists( 'testitem' ) )
1459 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1460 if ( $wgDBtype === 'postgres' )
1461 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1462 elseif ( $wgDBtype === 'oracle' )
1463 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1465 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1466 echo "OK, resuming.\n";
1471 $this->db->insert( 'testrun',
1473 'tr_date' => $this->db->timestamp(),
1474 'tr_mw_version' => $this->version,
1475 'tr_php_version' => phpversion(),
1476 'tr_db_version' => $this->db->getServerVersion(),
1477 'tr_uname' => php_uname()
1480 if ( $wgDBtype === 'postgres' )
1481 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1483 $this->curRun = $this->db->insertId();
1487 * Record an individual test item's success or failure to the db
1489 * @param $test String
1490 * @param $result Boolean
1492 function record( $test, $result ) {
1493 parent::record( $test, $result );
1494 $this->db->insert( 'testitem',
1496 'ti_run' => $this->curRun,
1498 'ti_success' => $result ? 1 : 0,
1504 class RemoteTestRecorder extends TestRecorder {
1507 $this->results = array();
1508 $this->ping( 'running' );
1511 function record( $test, $result ) {
1512 parent::record( $test, $result );
1513 $this->results[$test] = (bool)$result;
1517 $this->ping( 'complete', $this->results );
1522 * Inform a CodeReview instance that we've started or completed a test run...
1524 * @param $status string: "running" - tell it we've started
1525 * "complete" - provide test results array
1526 * "abort" - something went horribly awry
1527 * @param $results array of test name => true/false
1529 function ping( $status, $results = false ) {
1530 global $wgParserTestRemote, $IP;
1532 $remote = $wgParserTestRemote;
1533 $revId = SpecialVersion::getSvnRevision( $IP );
1534 $jsonResults = FormatJson::encode( $results );
1537 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1541 // Generate a hash MAC to validate our credentials
1548 if ( $status == "complete" ) {
1549 $message[] = $jsonResults;
1551 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1554 'action' => 'codetestupload',
1556 'repo' => $remote['repo'],
1557 'suite' => $remote['suite'],
1559 'status' => $status,
1562 if ( $status == "complete" ) {
1563 $postData['results'] = $jsonResults;
1565 $response = $this->post( $remote['api-url'], $postData );
1567 if ( $response === false ) {
1568 print "CodeReview info upload failed to reach server.\n";
1571 $responseData = FormatJson::decode( $response, true );
1572 if ( !is_array( $responseData ) ) {
1573 print "CodeReview API response not recognized...\n";
1574 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1577 if ( isset( $responseData['error'] ) ) {
1578 $code = $responseData['error']['code'];
1579 $info = $responseData['error']['info'];
1580 print "CodeReview info upload failed: $code $info\n";
1585 function post( $url, $data ) {
1586 return Http::post( $url, array( 'postData' => $data ) );
1590 class TestFileIterator implements Iterator {
1599 function __construct( $file, $parser = null ) {
1602 $this->file = $file;
1603 $this->fh = fopen( $this->file, "rt" );
1605 wfDie( "Couldn't open file '$file'\n" );
1608 $this->parser = $parser;
1610 if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1611 $this->lineNum = $this->index = 0;
1614 function setParser( ParserTest $parser ) {
1615 $this->parser = $parser;
1619 if ( fseek( $this->fh, 0 ) ) {
1620 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1630 function current() {
1635 return $this->index;
1639 if ( $this->readNextTest() ) {
1648 return $this->eof != true;
1651 function readNextTest() {
1655 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1658 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1659 $section = strtolower( $matches[1] );
1660 if ( $section == 'endarticle' ) {
1661 if ( !isset( $data['text'] ) ) {
1662 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1664 if ( !isset( $data['article'] ) ) {
1665 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1667 if ( $this->parser ) {
1668 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1675 if ( $section == 'endhooks' ) {
1676 if ( !isset( $data['hooks'] ) ) {
1677 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1679 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1680 $line = trim( $line );
1682 if ( $this->parser && !$this->parser->requireHook( $line ) ) {
1691 if ( $section == 'endfunctionhooks' ) {
1692 if ( !isset( $data['functionhooks'] ) ) {
1693 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1695 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1696 $line = trim( $line );
1698 if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
1707 if ( $section == 'end' ) {
1708 if ( !isset( $data['test'] ) ) {
1709 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1711 if ( !isset( $data['input'] ) ) {
1712 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1714 if ( !isset( $data['result'] ) ) {
1715 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1717 if ( !isset( $data['options'] ) ) {
1718 $data['options'] = '';
1720 if ( !isset( $data['config'] ) )
1721 $data['config'] = '';
1724 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1725 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
1731 if ( $this->parser &&
1732 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1733 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1739 if ( $this->parser ) {
1740 $this->test = array(
1741 'test' => $this->parser->chomp( $data['test'] ),
1742 'input' => $this->parser->chomp( $data['input'] ),
1743 'result' => $this->parser->chomp( $data['result'] ),
1744 'options' => $this->parser->chomp( $data['options'] ),
1745 'config' => $this->parser->chomp( $data['config'] ) );
1747 $this->test['test'] = $data['test'];
1751 if ( isset ( $data[$section] ) ) {
1752 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1754 $data[$section] = '';
1758 $data[$section] .= $line;