2 # Copyright (C) 2004 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 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record'. 'run-disabled' );
29 $optionsWithArgs = array( 'regex', 'seed', 'setversion' );
31 require_once( dirname(__FILE__) . '/commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
37 * @ingroup Maintenance
41 * boolean $color whereas output should be colorized
46 * boolean $showOutput Show test output
51 * boolean $useTemporaryTables Use temporary tables for the temporary database
53 private $useTemporaryTables = true;
56 * boolean $databaseSetupDone True if the database has been set up
58 private $databaseSetupDone = false;
61 * string $oldTablePrefix Original table prefix
63 private $oldTablePrefix;
65 private $maxFuzzTestLength = 300;
66 private $fuzzSeed = 0;
67 private $memoryLimit = 50;
70 * Sets terminal colorization and diff/quick modes depending on OS and
71 * command-line options (--color and --quick).
73 public function ParserTest() {
76 # Only colorize output if stdout is a terminal.
77 $this->color = !wfIsWindows() && posix_isatty(1);
79 if( isset( $options['color'] ) ) {
80 switch( $options['color'] ) {
90 $this->term = $this->color
91 ? new AnsiTermColorer()
92 : new DummyTermColorer();
94 $this->showDiffs = !isset( $options['quick'] );
95 $this->showProgress = !isset( $options['quiet'] );
96 $this->showFailure = !(
97 isset( $options['quiet'] )
98 && ( isset( $options['record'] )
99 || isset( $options['compare'] ) ) ); // redundant output
101 $this->showOutput = isset( $options['show-output'] );
104 if (isset($options['regex'])) {
105 if ( isset( $options['record'] ) ) {
106 echo "Warning: --record cannot be used with --regex, disabling --record\n";
107 unset( $options['record'] );
109 $this->regex = $options['regex'];
115 if( isset( $options['record'] ) ) {
116 $this->recorder = new DbTestRecorder( $this );
117 } elseif( isset( $options['compare'] ) ) {
118 $this->recorder = new DbTestPreviewer( $this );
119 } elseif( isset( $options['upload'] ) ) {
120 $this->recorder = new RemoteTestRecorder( $this );
122 $this->recorder = new TestRecorder( $this );
124 $this->keepUploads = isset( $options['keep-uploads'] );
126 if ( isset( $options['seed'] ) ) {
127 $this->fuzzSeed = intval( $options['seed'] ) - 1;
130 $this->runDisabled = isset( $options['run-disabled'] );
132 $this->hooks = array();
133 $this->functionHooks = array();
137 * Remove last character if it is a newline
139 private function chomp($s) {
140 if (substr($s, -1) === "\n") {
141 return substr($s, 0, -1);
149 * Run a fuzz test series
150 * Draw input from a set of test files
152 function fuzzTest( $filenames ) {
153 $dict = $this->getFuzzInput( $filenames );
154 $dictSize = strlen( $dict );
155 $logMaxLength = log( $this->maxFuzzTestLength );
156 $this->setupDatabase();
157 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
162 $opts = ParserOptions::newFromUser( $user );
163 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
166 // Generate test input
167 mt_srand( ++$this->fuzzSeed );
168 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
170 while ( strlen( $input ) < $totalLength ) {
171 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
172 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
173 $offset = mt_rand( 0, $dictSize - $hairLength );
174 $input .= substr( $dict, $offset, $hairLength );
177 $this->setupGlobals();
178 $parser = $this->getParser();
181 $parser->parse( $input, $title, $opts );
183 } catch ( Exception $exception ) {
188 echo "Test failed with seed {$this->fuzzSeed}\n";
197 $this->teardownGlobals();
198 $parser->__destruct();
200 if ( $numTotal % 100 == 0 ) {
201 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
202 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
204 echo "Out of memory:\n";
205 $memStats = $this->getMemoryBreakdown();
206 foreach ( $memStats as $name => $usage ) {
207 echo "$name: $usage\n";
216 * Get an input dictionary from a set of parser test files
218 function getFuzzInput( $filenames ) {
220 foreach( $filenames as $filename ) {
221 $contents = file_get_contents( $filename );
222 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
223 foreach ( $matches[1] as $match ) {
224 $dict .= $match . "\n";
231 * Get a memory usage breakdown
233 function getMemoryBreakdown() {
235 foreach ( $GLOBALS as $name => $value ) {
236 $memStats['$'.$name] = strlen( serialize( $value ) );
238 $classes = get_declared_classes();
239 foreach ( $classes as $class ) {
240 $rc = new ReflectionClass( $class );
241 $props = $rc->getStaticProperties();
242 $memStats[$class] = strlen( serialize( $props ) );
243 $methods = $rc->getMethods();
244 foreach ( $methods as $method ) {
245 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
248 $functions = get_defined_functions();
249 foreach ( $functions['user'] as $function ) {
250 $rf = new ReflectionFunction( $function );
251 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
262 * Run a series of tests listed in the given text files.
263 * Each test consists of a brief description, wikitext input,
264 * and the expected HTML output.
266 * Prints status updates on stdout and counts up the total
267 * number and percentage of passed tests.
269 * @param array of strings $filenames
270 * @return bool True if passed all tests, false if any tests failed.
272 public function runTestsFromFiles( $filenames ) {
273 $this->recorder->start();
274 $this->setupDatabase();
276 foreach( $filenames as $filename ) {
277 $ok = $this->runFile( $filename ) && $ok;
279 $this->teardownDatabase();
280 $this->recorder->report();
281 $this->recorder->end();
285 private function runFile( $filename ) {
286 $infile = fopen( $filename, 'rt' );
288 wfDie( "Couldn't open file '$filename'\n" );
291 $relative = wfRelativePath( $filename, $IP );
292 $this->showRunFile( $relative );
299 while( false !== ($line = fgets( $infile ) ) ) {
302 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
303 $section = strtolower( $matches[1] );
304 if( $section == 'endarticle') {
305 if( !isset( $data['text'] ) ) {
306 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
308 if( !isset( $data['article'] ) ) {
309 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
311 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
316 if( $section == 'endhooks' ) {
317 if( !isset( $data['hooks'] ) ) {
318 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
320 foreach( explode( "\n", $data['hooks'] ) as $line ) {
321 $line = trim( $line );
323 $this->requireHook( $line );
330 if( $section == 'endfunctionhooks' ) {
331 if( !isset( $data['functionhooks'] ) ) {
332 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
334 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
335 $line = trim( $line );
337 $this->requireFunctionHook( $line );
344 if( $section == 'end' ) {
345 if( !isset( $data['test'] ) ) {
346 wfDie( "'end' without 'test' at line $n of $filename\n" );
348 if( !isset( $data['input'] ) ) {
349 wfDie( "'end' without 'input' at line $n of $filename\n" );
351 if( !isset( $data['result'] ) ) {
352 wfDie( "'end' without 'result' at line $n of $filename\n" );
354 if( !isset( $data['options'] ) ) {
355 $data['options'] = '';
358 $data['options'] = $this->chomp( $data['options'] );
360 if (!isset( $data['config'] ) )
361 $data['config'] = '';
363 if ( (preg_match('/\\bdisabled\\b/i', $data['options'])
364 || !preg_match("/{$this->regex}/i", $data['test'])) && !$this->runDisabled ) {
370 $result = $this->runTest(
371 $this->chomp( $data['test'] ),
372 $this->chomp( $data['input'] ),
373 $this->chomp( $data['result'] ),
374 $this->chomp( $data['options'] ),
375 $this->chomp( $data['config'] )
377 $ok = $ok && $result;
378 $this->recorder->record( $this->chomp( $data['test'] ), $result );
383 if ( isset ($data[$section] ) ) {
384 wfDie( "duplicate section '$section' at line $n of $filename\n" );
386 $data[$section] = '';
390 $data[$section] .= $line;
393 if ( $this->showProgress ) {
400 * Get a Parser object
402 function getParser() {
403 global $wgParserConf;
404 $class = $wgParserConf['class'];
405 $parser = new $class( $wgParserConf );
406 foreach( $this->hooks as $tag => $callback ) {
407 $parser->setHook( $tag, $callback );
409 foreach( $this->functionHooks as $tag => $bits ) {
410 list( $callback, $flags ) = $bits;
411 $parser->setFunctionHook( $tag, $callback, $flags );
413 wfRunHooks( 'ParserTestParser', array( &$parser ) );
418 * Run a given wikitext input through a freshly-constructed wiki parser,
419 * and compare the output against the expected results.
420 * Prints status and explanatory messages to stdout.
422 * @param string $input Wikitext to try rendering
423 * @param string $result Result to output
426 private function runTest( $desc, $input, $result, $opts, $config ) {
427 if( $this->showProgress ) {
428 $this->showTesting( $desc );
431 $opts = $this->parseOptions( $opts );
432 $this->setupGlobals($opts, $config);
435 $options = ParserOptions::newFromUser( $user );
437 if ( isset( $opts['math'] ) ) {
438 # XXX this should probably be done by the ParserOptions
439 $options->setUseTex(true);
443 if (isset( $opts['title'] ) ) {
444 $titleText = $opts['title'];
447 $titleText = 'Parser test';
450 $noxml = isset( $opts['noxml'] );
451 $local = isset( $opts['local'] );
452 $parser = $this->getParser();
453 $title = Title::newFromText( $titleText );
456 if( isset( $opts['pst'] ) ) {
457 $out = $parser->preSaveTransform( $input, $title, $user, $options );
458 } elseif( isset( $opts['msg'] ) ) {
459 $out = $parser->transformMsg( $input, $options );
460 } elseif( isset( $opts['section'] ) ) {
461 $section = $opts['section'];
462 $out = $parser->getSection( $input, $section );
463 } elseif( isset( $opts['replace'] ) ) {
464 $section = $opts['replace'][0];
465 $replace = $opts['replace'][1];
466 $out = $parser->replaceSection( $input, $section, $replace );
467 } elseif( isset( $opts['comment'] ) ) {
468 $linker = $user->getSkin();
469 $out = $linker->formatComment( $input, $title, $local );
471 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
472 $out = $output->getText();
474 if (isset( $opts['ill'] ) ) {
475 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
476 } elseif( isset( $opts['cat'] ) ) {
478 $wgOut->addCategoryLinks($output->getCategories());
479 $cats = $wgOut->getCategoryLinks();
480 if ( isset( $cats['normal'] ) ) {
481 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
487 $result = $this->tidy($result);
490 $this->teardownGlobals();
492 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
493 return $this->showSuccess( $desc );
495 return $this->showFailure( $desc, $result, $out );
501 * Use a regex to find out the value of an option
502 * @param $key name of option val to retrieve
503 * @param $opts Options array to look in
504 * @param $defaults Default value returned if not found
506 private static function getOptionValue( $key, $opts, $default ) {
507 $key = strtolower( $key );
508 if( isset( $opts[$key] ) ) {
515 private function parseOptions( $instring ) {
517 $lines = explode( "\n", $instring );
522 // foo=bar,"baz quux"
546 \[\[[^]]*\]\] # Link target
554 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
555 foreach( $matches as $bits ) {
556 $match = array_shift( $bits );
557 $key = strtolower( array_shift( $bits ) );
558 if( count( $bits ) == 0 ) {
560 } elseif( count( $bits ) == 1 ) {
561 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
564 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
571 private function cleanupOption( $opt ) {
572 if( substr( $opt, 0, 1 ) == '"' ) {
573 return substr( $opt, 1, -1 );
575 if( substr( $opt, 0, 2 ) == '[[' ) {
576 return substr( $opt, 2, -2 );
582 * Set up the global variables for a consistent environment for each test.
583 * Ideally this should replace the global configuration entirely.
585 private function setupGlobals($opts = '', $config = '') {
586 if( !isset( $this->uploadDir ) ) {
587 $this->uploadDir = $this->setupUploadDir();
590 # Find out values for some special options.
592 self::getOptionValue( 'language', $opts, 'en' );
594 self::getOptionValue( 'variant', $opts, false );
596 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
597 $linkHolderBatchSize =
598 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
601 'wgServer' => 'http://localhost',
602 'wgScript' => '/index.php',
603 'wgScriptPath' => '/',
604 'wgArticlePath' => '/wiki/$1',
605 'wgActionPaths' => array(),
606 'wgLocalFileRepo' => array(
607 'class' => 'LocalRepo',
609 'directory' => $this->uploadDir,
610 'url' => 'http://example.com/images',
612 'transformVia404' => false,
614 'wgEnableUploads' => true,
615 'wgStyleSheetPath' => '/skins',
616 'wgSitename' => 'MediaWiki',
617 'wgServerName' => 'Britney Spears',
618 'wgLanguageCode' => $lang,
619 'wgContLanguageCode' => $lang,
620 'wgDBprefix' => 'parsertest_',
621 'wgRawHtml' => isset( $opts['rawhtml'] ),
623 'wgContLang' => null,
624 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
625 'wgMaxTocLevel' => $maxtoclevel,
626 'wgCapitalLinks' => true,
627 'wgNoFollowLinks' => true,
628 'wgNoFollowDomainExceptions' => array(),
629 'wgThumbnailScriptPath' => false,
631 'wgLocaltimezone' => 'UTC',
632 'wgAllowExternalImages' => true,
633 'wgUseTidy' => false,
634 'wgDefaultLanguageVariant' => $variant,
635 'wgVariantArticlePath' => false,
636 'wgGroupPermissions' => array( '*' => array(
637 'createaccount' => true,
640 'createpage' => true,
641 'createtalk' => true,
643 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
644 'wgDefaultExternalStore' => array(),
645 'wgForeignFileRepos' => array(),
646 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
647 'wgEnforceHtmlIds' => true,
648 'wgExternalLinkTarget' => false,
649 'wgAlwaysUseTidy' => false,
651 'wgWellFormedXml' => true,
655 $configLines = explode( "\n", $config );
657 foreach( $configLines as $line ) {
658 list( $var, $value ) = explode( '=', $line, 2 );
660 $settings[$var] = eval("return $value;" );
664 $this->savedGlobals = array();
665 foreach( $settings as $var => $val ) {
666 $this->savedGlobals[$var] = $GLOBALS[$var];
667 $GLOBALS[$var] = $val;
669 $langObj = Language::factory( $lang );
670 $GLOBALS['wgLang'] = $langObj;
671 $GLOBALS['wgContLang'] = $langObj;
672 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
674 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
677 $wgUser = new User();
681 * List of temporary tables to create, without prefix.
682 * Some of these probably aren't necessary.
684 private function listTables() {
686 $tables = array('user', 'page', 'page_restrictions',
687 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
688 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
689 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
690 'recentchanges', 'watchlist', 'math', 'interwiki',
691 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
692 'archive', 'user_groups', 'page_props', 'category'
695 if ($wgDBtype === 'mysql')
696 array_push( $tables, 'searchindex' );
698 // Allow extensions to add to the list of tables to duplicate;
699 // may be necessary if they hook into page save or other code
700 // which will require them while running tests.
701 wfRunHooks( 'ParserTestTables', array( &$tables ) );
707 * Set up a temporary set of wiki tables to work with for the tests.
708 * Currently this will only be done once per run, and any changes to
709 * the db will be visible to later tests in the run.
711 private function setupDatabase() {
712 global $wgDBprefix, $wgDBtype;
713 if ( $this->databaseSetupDone ) {
716 if ( $wgDBprefix === 'parsertest_' ) {
717 throw new MWException( 'setupDatabase should be called before setupGlobals' );
719 $this->databaseSetupDone = true;
720 $this->oldTablePrefix = $wgDBprefix;
722 # CREATE TEMPORARY TABLE breaks if there is more than one server
723 # FIXME: r40209 makes temporary tables break even with just one server
724 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
725 if ( true || wfGetLB()->getServerCount() != 1 ) {
726 $this->useTemporaryTables = false;
729 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
731 $db = wfGetDB( DB_MASTER );
732 $tables = $this->listTables();
734 if ( !( $wgDBtype == 'mysql' && strcmp( $db->getServerVersion(), '4.1' ) < 0 ) ) {
735 # Database that supports CREATE TABLE ... LIKE
737 if( $wgDBtype == 'postgres' ) {
738 $def = 'INCLUDING DEFAULTS';
739 $temporary = 'TEMPORARY';
743 foreach ( $tables as $tbl ) {
744 # Clean up from previous aborted run. So that table escaping
745 # works correctly across DB engines, we need to change the pre-
746 # fix back and forth so tableName() works right.
747 $this->changePrefix( $this->oldTablePrefix );
748 $oldTableName = $db->tableName( $tbl );
749 $this->changePrefix( 'parsertest_' );
750 $newTableName = $db->tableName( $tbl );
752 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' ) {
753 $db->query( "DROP TABLE $newTableName" );
756 $db->query( "CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)" );
759 # Hack for MySQL versions < 4.1, which don't support
760 # "CREATE TABLE ... LIKE". Note that
761 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
762 # would not create the indexes we need....
764 # Note that we don't bother changing around the prefixes here be-
765 # cause we know we're using MySQL anyway.
766 foreach ($tables as $tbl) {
767 $oldTableName = $db->tableName( $tbl );
768 $res = $db->query("SHOW CREATE TABLE $oldTableName");
769 $row = $db->fetchRow($res);
771 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
772 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
773 if ($create === $create_tmp) {
774 # Couldn't do replacement
775 wfDie("could not create temporary table $tbl");
777 $db->query($create_tmp);
781 $this->changePrefix( 'parsertest_' );
783 # Hack: insert a few Wikipedia in-project interwiki prefixes,
784 # for testing inter-language links
785 $db->insert( 'interwiki', array(
786 array( 'iw_prefix' => 'wikipedia',
787 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
789 array( 'iw_prefix' => 'meatball',
790 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
792 array( 'iw_prefix' => 'zh',
793 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
795 array( 'iw_prefix' => 'es',
796 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
798 array( 'iw_prefix' => 'fr',
799 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
801 array( 'iw_prefix' => 'ru',
802 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
806 # Hack: Insert an image to work with
807 $db->insert( 'image', array(
808 'img_name' => 'Foobar.jpg',
810 'img_description' => 'Some lame file',
812 'img_user_text' => 'WikiSysop',
813 'img_timestamp' => $db->timestamp( '20010115123500' ),
817 'img_media_type' => MEDIATYPE_BITMAP,
818 'img_major_mime' => "image",
819 'img_minor_mime' => "jpeg",
820 'img_metadata' => serialize( array() ),
823 # Update certain things in site_stats
824 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
826 # Reinitialise the LocalisationCache to match the database state
827 Language::getLocalisationCache()->unloadAll();
831 * Change the table prefix on all open DB connections/
833 protected function changePrefix( $prefix ) {
835 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
836 $wgDBprefix = $prefix;
839 public function changeLBPrefix( $lb, $prefix ) {
840 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
843 public function changeDBPrefix( $db, $prefix ) {
844 $db->tablePrefix( $prefix );
847 private function teardownDatabase() {
849 if ( !$this->databaseSetupDone ) {
852 $this->changePrefix( $this->oldTablePrefix );
853 $this->databaseSetupDone = false;
854 if ( $this->useTemporaryTables ) {
855 # Don't need to do anything
860 $tables = $this->listTables();
861 $db = wfGetDB( DB_MASTER );
862 foreach ( $tables as $table ) {
863 $db->query( "DROP TABLE `parsertest_$table`" );
868 * Create a dummy uploads directory which will contain a couple
869 * of files in order to pass existence tests.
870 * @return string The directory
872 private function setupUploadDir() {
874 if ( $this->keepUploads ) {
875 $dir = wfTempDir() . '/mwParser-images';
876 if ( is_dir( $dir ) ) {
880 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
883 wfDebug( "Creating upload directory $dir\n" );
884 if ( file_exists( $dir ) ) {
885 wfDebug( "Already exists!\n" );
888 wfMkdirParents( $dir . '/3/3a' );
889 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
894 * Restore default values and perform any necessary clean-up
895 * after each test runs.
897 private function teardownGlobals() {
898 RepoGroup::destroySingleton();
899 FileCache::destroySingleton();
900 LinkCache::singleton()->clear();
901 foreach( $this->savedGlobals as $var => $val ) {
902 $GLOBALS[$var] = $val;
904 if( isset( $this->uploadDir ) ) {
905 $this->teardownUploadDir( $this->uploadDir );
906 unset( $this->uploadDir );
911 * Remove the dummy uploads directory
913 private function teardownUploadDir( $dir ) {
914 if ( $this->keepUploads ) {
918 // delete the files first, then the dirs.
921 "$dir/3/3a/Foobar.jpg",
922 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
923 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
924 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
925 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
935 "$dir/thumb/3/3a/Foobar.jpg",
945 * Delete the specified files, if they exist.
946 * @param array $files full paths to files to delete.
948 private static function deleteFiles( $files ) {
949 foreach( $files as $file ) {
950 if( file_exists( $file ) ) {
957 * Delete the specified directories, if they exist. Must be empty.
958 * @param array $dirs full paths to directories to delete.
960 private static function deleteDirs( $dirs ) {
961 foreach( $dirs as $dir ) {
962 if( is_dir( $dir ) ) {
969 * "Running test $desc..."
971 protected function showTesting( $desc ) {
972 print "Running test $desc... ";
976 * Print a happy success message.
978 * @param string $desc The test name
981 protected function showSuccess( $desc ) {
982 if( $this->showProgress ) {
983 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
989 * Print a failure message and provide some explanatory output
990 * about what went wrong if so configured.
992 * @param string $desc The test name
993 * @param string $result Expected HTML output
994 * @param string $html Actual HTML output
997 protected function showFailure( $desc, $result, $html ) {
998 if( $this->showFailure ) {
999 if( !$this->showProgress ) {
1000 # In quiet mode we didn't show the 'Testing' message before the
1001 # test, in case it succeeded. Show it now:
1002 $this->showTesting( $desc );
1004 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1005 if ( $this->showOutput ) {
1006 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1008 if( $this->showDiffs ) {
1009 print $this->quickDiff( $result, $html );
1010 if( !$this->wellFormed( $html ) ) {
1011 print "XML error: $this->mXmlError\n";
1019 * Run given strings through a diff and return the (colorized) output.
1020 * Requires writable /tmp directory and a 'diff' command in the PATH.
1022 * @param string $input
1023 * @param string $output
1024 * @param string $inFileTail Tailing for the input file name
1025 * @param string $outFileTail Tailing for the output file name
1028 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
1029 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1031 $infile = "$prefix-$inFileTail";
1032 $this->dumpToFile( $input, $infile );
1034 $outfile = "$prefix-$outFileTail";
1035 $this->dumpToFile( $output, $outfile );
1037 $diff = `diff -au $infile $outfile`;
1041 return $this->colorDiff( $diff );
1045 * Write the given string to a file, adding a final newline.
1047 * @param string $data
1048 * @param string $filename
1050 private function dumpToFile( $data, $filename ) {
1051 $file = fopen( $filename, "wt" );
1052 fwrite( $file, $data . "\n" );
1057 * Colorize unified diff output if set for ANSI color output.
1058 * Subtractions are colored blue, additions red.
1060 * @param string $text
1063 protected function colorDiff( $text ) {
1064 return preg_replace(
1065 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1066 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1067 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1072 * Show "Reading tests from ..."
1074 * @param String $path
1076 protected function showRunFile( $path ){
1077 print $this->term->color( 1 ) .
1078 "Reading tests from \"$path\"..." .
1079 $this->term->reset() .
1084 * Insert a temporary test article
1085 * @param string $name the title, including any prefix
1086 * @param string $text the article text
1087 * @param int $line the input line number, for reporting errors
1089 private function addArticle($name, $text, $line) {
1090 $this->setupGlobals();
1091 $title = Title::newFromText( $name );
1092 if ( is_null($title) ) {
1093 wfDie( "invalid title at line $line\n" );
1096 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1098 wfDie( "duplicate article at line $line\n" );
1101 $art = new Article($title);
1102 $art->insertNewArticle($text, '', false, false );
1103 $this->teardownGlobals();
1107 * Steal a callback function from the primary parser, save it for
1108 * application to our scary parser. If the hook is not installed,
1109 * die a painful dead to warn the others.
1110 * @param string $name
1112 private function requireHook( $name ) {
1114 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1115 if( isset( $wgParser->mTagHooks[$name] ) ) {
1116 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1118 wfDie( "This test suite requires the '$name' hook extension.\n" );
1123 * Steal a callback function from the primary parser, save it for
1124 * application to our scary parser. If the hook is not installed,
1125 * die a painful dead to warn the others.
1126 * @param string $name
1128 private function requireFunctionHook( $name ) {
1130 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1131 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1132 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1134 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1139 * Run the "tidy" command on text if the $wgUseTidy
1142 * @param string $text the text to tidy
1146 private function tidy( $text ) {
1149 $text = Parser::tidy($text);
1154 private function wellFormed( $text ) {
1156 Sanitizer::hackDocType() .
1161 $parser = xml_parser_create( "UTF-8" );
1163 # case folding violates XML standard, turn it off
1164 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1166 if( !xml_parse( $parser, $html, true ) ) {
1167 $err = xml_error_string( xml_get_error_code( $parser ) );
1168 $position = xml_get_current_byte_index( $parser );
1169 $fragment = $this->extractFragment( $html, $position );
1170 $this->mXmlError = "$err at byte $position:\n$fragment";
1171 xml_parser_free( $parser );
1174 xml_parser_free( $parser );
1178 private function extractFragment( $text, $position ) {
1179 $start = max( 0, $position - 10 );
1180 $before = $position - $start;
1182 $this->term->color( 34 ) .
1183 substr( $text, $start, $before ) .
1184 $this->term->color( 0 ) .
1185 $this->term->color( 31 ) .
1186 $this->term->color( 1 ) .
1187 substr( $text, $position, 1 ) .
1188 $this->term->color( 0 ) .
1189 $this->term->color( 34 ) .
1190 substr( $text, $position + 1, 9 ) .
1191 $this->term->color( 0 ) .
1193 $display = str_replace( "\n", ' ', $fragment );
1195 str_repeat( ' ', $before ) .
1196 $this->term->color( 31 ) .
1198 $this->term->color( 0 );
1199 return "$display\n$caret";
1203 class AnsiTermColorer {
1204 function __construct() {
1208 * Return ANSI terminal escape code for changing text attribs/color
1210 * @param string $color Semicolon-separated list of attribute/color codes
1213 public function color( $color ) {
1214 global $wgCommandLineDarkBg;
1215 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1216 return "\x1b[{$light}{$color}m";
1220 * Return ANSI terminal escape code for restoring default text attributes
1224 public function reset() {
1225 return $this->color( 0 );
1229 /* A colour-less terminal */
1230 class DummyTermColorer {
1231 public function color( $color ) {
1235 public function reset() {
1240 class TestRecorder {
1244 function __construct( $parent ) {
1245 $this->parent = $parent;
1246 $this->term = $parent->term;
1254 function record( $test, $result ) {
1256 $this->success += ($result ? 1 : 0);
1264 if( $this->total > 0 ) {
1265 $this->reportPercentage( $this->success, $this->total );
1267 wfDie( "No tests found.\n" );
1271 function reportPercentage( $success, $total ) {
1272 $ratio = wfPercent( 100 * $success / $total );
1273 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1274 if( $success == $total ) {
1275 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1277 $failed = $total - $success ;
1278 print $this->term->color( 31 ) . "$failed tests failed!";
1280 print $this->term->reset() . "\n";
1281 return ($success == $total);
1285 class DbTestPreviewer extends TestRecorder {
1286 protected $lb; ///< Database load balancer
1287 protected $db; ///< Database connection to the main DB
1288 protected $curRun; ///< run ID number for the current run
1289 protected $prevRun; ///< run ID number for the previous run, if any
1290 protected $results; ///< Result array
1293 * This should be called before the table prefix is changed
1295 function __construct( $parent ) {
1296 parent::__construct( $parent );
1297 $this->lb = wfGetLBFactory()->newMainLB();
1298 // This connection will have the wiki's table prefix, not parsertest_
1299 $this->db = $this->lb->getConnection( DB_MASTER );
1303 * Set up result recording; insert a record for the run with the date
1304 * and all that fun stuff
1307 global $wgDBtype, $wgDBprefix;
1310 if( ! $this->db->tableExists( 'testrun' )
1311 or ! $this->db->tableExists( 'testitem' ) )
1313 print "WARNING> `testrun` table not found in database.\n";
1314 $this->prevRun = false;
1316 // We'll make comparisons against the previous run later...
1317 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1319 $this->results = array();
1322 function record( $test, $result ) {
1323 parent::record( $test, $result );
1324 $this->results[$test] = $result;
1328 if( $this->prevRun ) {
1329 // f = fail, p = pass, n = nonexistent
1330 // codes show before then after
1332 'fp' => 'previously failing test(s) now PASSING! :)',
1333 'pn' => 'previously PASSING test(s) removed o_O',
1334 'np' => 'new PASSING test(s) :)',
1336 'pf' => 'previously passing test(s) now FAILING! :(',
1337 'fn' => 'previously FAILING test(s) removed O_o',
1338 'nf' => 'new FAILING test(s) :(',
1339 'ff' => 'still FAILING test(s) :(',
1342 $prevResults = array();
1344 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1345 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1346 foreach ( $res as $row ) {
1347 if ( !$this->parent->regex
1348 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1350 $prevResults[$row->ti_name] = $row->ti_success;
1354 $combined = array_keys( $this->results + $prevResults );
1356 # Determine breakdown by change type
1357 $breakdown = array();
1358 foreach ( $combined as $test ) {
1359 if ( !isset( $prevResults[$test] ) ) {
1361 } elseif ( $prevResults[$test] == 1 ) {
1363 } else /* if ( $prevResults[$test] == 0 )*/ {
1366 if ( !isset( $this->results[$test] ) ) {
1368 } elseif ( $this->results[$test] == 1 ) {
1370 } else /*if ( $this->results[$test] == 0 ) */ {
1373 $code = $before . $after;
1374 if ( isset( $table[$code] ) ) {
1375 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1380 foreach ( $table as $code => $label ) {
1381 if( !empty( $breakdown[$code] ) ) {
1382 $count = count($breakdown[$code]);
1383 printf( "\n%4d %s\n", $count, $label );
1384 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1385 print " * $differing_test_name [$statusInfo]\n";
1390 print "No previous test runs to compare against.\n";
1397 ** Returns a string giving information about when a test last had a status change.
1398 ** Could help to track down when regressions were introduced, as distinct from tests
1399 ** which have never passed (which are more change requests than regressions).
1401 private function getTestStatusInfo($testname, $after) {
1403 // If we're looking at a test that has just been removed, then say when it first appeared.
1404 if ( $after == 'n' ) {
1405 $changedRun = $this->db->selectField ( 'testitem',
1407 array( 'ti_name' => $testname ),
1409 $appear = $this->db->selectRow ( 'testrun',
1410 array( 'tr_date', 'tr_mw_version' ),
1411 array( 'tr_id' => $changedRun ),
1413 return "First recorded appearance: "
1414 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1415 . ", " . $appear->tr_mw_version;
1418 // Otherwise, this test has previous recorded results.
1419 // See when this test last had a different result to what we're seeing now.
1421 'ti_name' => $testname,
1422 'ti_success' => ($after == 'f' ? "1" : "0") );
1423 if ( $this->curRun ) {
1424 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1427 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1429 // If no record of ever having had a different result.
1430 if ( is_null ( $changedRun ) ) {
1431 if ($after == "f") {
1432 return "Has never passed";
1434 return "Has never failed";
1438 // Otherwise, we're looking at a test whose status has changed.
1439 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1440 // In this situation, give as much info as we can as to when it changed status.
1441 $pre = $this->db->selectRow ( 'testrun',
1442 array( 'tr_date', 'tr_mw_version' ),
1443 array( 'tr_id' => $changedRun ),
1445 $post = $this->db->selectRow ( 'testrun',
1446 array( 'tr_date', 'tr_mw_version' ),
1447 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1449 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1453 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1457 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1458 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1464 * Commit transaction and clean up for result recording
1467 $this->lb->commitMasterChanges();
1468 $this->lb->closeAll();
1474 class DbTestRecorder extends DbTestPreviewer {
1476 * Set up result recording; insert a record for the run with the date
1477 * and all that fun stuff
1480 global $wgDBtype, $wgDBprefix, $options;
1483 if( ! $this->db->tableExists( 'testrun' )
1484 or ! $this->db->tableExists( 'testitem' ) )
1486 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1487 if ($wgDBtype === 'postgres')
1488 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1490 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1491 echo "OK, resuming.\n";
1496 $this->db->insert( 'testrun',
1498 'tr_date' => $this->db->timestamp(),
1499 'tr_mw_version' => isset( $options['setversion'] ) ?
1500 $options['setversion'] : SpecialVersion::getVersion(),
1501 'tr_php_version' => phpversion(),
1502 'tr_db_version' => $this->db->getServerVersion(),
1503 'tr_uname' => php_uname()
1506 if ($wgDBtype === 'postgres')
1507 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1509 $this->curRun = $this->db->insertId();
1513 * Record an individual test item's success or failure to the db
1514 * @param string $test
1515 * @param bool $result
1517 function record( $test, $result ) {
1518 parent::record( $test, $result );
1519 $this->db->insert( 'testitem',
1521 'ti_run' => $this->curRun,
1523 'ti_success' => $result ? 1 : 0,
1529 class RemoteTestRecorder extends TestRecorder {
1532 $this->results = array();
1533 $this->ping( 'running' );
1536 function record( $test, $result ) {
1537 parent::record( $test, $result );
1538 $this->results[$test] = (bool)$result;
1542 $this->ping( 'complete', $this->results );
1547 * Inform a CodeReview instance that we've started or completed a test run...
1548 * @param $remote array: info on remote target
1549 * @param $status string: "running" - tell it we've started
1550 * "complete" - provide test results array
1551 * "abort" - something went horribly awry
1552 * @param $data array of test name => true/false
1554 function ping( $status, $results=false ) {
1555 global $wgParserTestRemote, $IP;
1557 $remote = $wgParserTestRemote;
1558 $revId = SpecialVersion::getSvnRevision( $IP );
1559 $jsonResults = json_encode( $results );
1562 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1566 // Generate a hash MAC to validate our credentials
1573 if( $status == "complete" ) {
1574 $message[] = $jsonResults;
1576 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1579 'action' => 'codetestupload',
1581 'repo' => $remote['repo'],
1582 'suite' => $remote['suite'],
1584 'status' => $status,
1587 if( $status == "complete" ) {
1588 $postData['results'] = $jsonResults;
1590 $response = $this->post( $remote['api-url'], $postData );
1592 if( $response === false ) {
1593 print "CodeReview info upload failed to reach server.\n";
1596 $responseData = json_decode( $response, true );
1597 if( !is_array( $responseData ) ) {
1598 print "CodeReview API response not recognized...\n";
1599 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1602 if( isset( $responseData['error'] ) ) {
1603 $code = $responseData['error']['code'];
1604 $info = $responseData['error']['info'];
1605 print "CodeReview info upload failed: $code $info\n";
1610 function post( $url, $data ) {
1611 // @fixme: for whatever reason, I get a 417 fail when using CURL's multipart form submit.
1612 // If we do form URL encoding ourselves, though, it should work.
1613 return Http::post( $url, array( 'postdata' => wfArrayToCGI( $data ) ) );