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 if ( !defined( "NO_COMMAND_LINE" ) ) {
32 require_once( dirname(__FILE__) . '/commandLine.inc' );
34 require_once( "$IP/maintenance/parserTestsParserHook.php" );
35 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
36 require_once( "$IP/maintenance/parserTestsParserTime.php" );
39 * @ingroup Maintenance
43 * boolean $color whereas output should be colorized
48 * boolean $showOutput Show test output
53 * boolean $useTemporaryTables Use temporary tables for the temporary database
55 private $useTemporaryTables = true;
58 * boolean $databaseSetupDone True if the database has been set up
60 private $databaseSetupDone = false;
63 * string $oldTablePrefix Original table prefix
65 private $oldTablePrefix;
67 private $maxFuzzTestLength = 300;
68 private $fuzzSeed = 0;
69 private $memoryLimit = 50;
72 * Sets terminal colorization and diff/quick modes depending on OS and
73 * command-line options (--color and --quick).
75 public function ParserTest() {
78 # Only colorize output if stdout is a terminal.
79 $this->color = !wfIsWindows() && posix_isatty(1);
81 if( isset( $options['color'] ) ) {
82 switch( $options['color'] ) {
92 $this->term = $this->color
93 ? new AnsiTermColorer()
94 : new DummyTermColorer();
96 $this->showDiffs = !isset( $options['quick'] );
97 $this->showProgress = !isset( $options['quiet'] );
98 $this->showFailure = !(
99 isset( $options['quiet'] )
100 && ( isset( $options['record'] )
101 || isset( $options['compare'] ) ) ); // redundant output
103 $this->showOutput = isset( $options['show-output'] );
106 if (isset($options['regex'])) {
107 if ( isset( $options['record'] ) ) {
108 echo "Warning: --record cannot be used with --regex, disabling --record\n";
109 unset( $options['record'] );
111 $this->regex = $options['regex'];
117 if( isset( $options['record'] ) ) {
118 $this->recorder = new DbTestRecorder( $this );
119 } elseif( isset( $options['compare'] ) ) {
120 $this->recorder = new DbTestPreviewer( $this );
121 } elseif( isset( $options['upload'] ) ) {
122 $this->recorder = new RemoteTestRecorder( $this );
124 $this->recorder = new TestRecorder( $this );
126 $this->keepUploads = isset( $options['keep-uploads'] );
128 if ( isset( $options['seed'] ) ) {
129 $this->fuzzSeed = intval( $options['seed'] ) - 1;
132 $this->runDisabled = isset( $options['run-disabled'] );
134 $this->hooks = array();
135 $this->functionHooks = array();
139 * Remove last character if it is a newline
141 private function chomp($s) {
142 if (substr($s, -1) === "\n") {
143 return substr($s, 0, -1);
151 * Run a fuzz test series
152 * Draw input from a set of test files
154 function fuzzTest( $filenames ) {
155 $dict = $this->getFuzzInput( $filenames );
156 $dictSize = strlen( $dict );
157 $logMaxLength = log( $this->maxFuzzTestLength );
158 $this->setupDatabase();
159 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
164 $opts = ParserOptions::newFromUser( $user );
165 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
168 // Generate test input
169 mt_srand( ++$this->fuzzSeed );
170 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
172 while ( strlen( $input ) < $totalLength ) {
173 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
174 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
175 $offset = mt_rand( 0, $dictSize - $hairLength );
176 $input .= substr( $dict, $offset, $hairLength );
179 $this->setupGlobals();
180 $parser = $this->getParser();
183 $parser->parse( $input, $title, $opts );
185 } catch ( Exception $exception ) {
190 echo "Test failed with seed {$this->fuzzSeed}\n";
199 $this->teardownGlobals();
200 $parser->__destruct();
202 if ( $numTotal % 100 == 0 ) {
203 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
204 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
206 echo "Out of memory:\n";
207 $memStats = $this->getMemoryBreakdown();
208 foreach ( $memStats as $name => $usage ) {
209 echo "$name: $usage\n";
218 * Get an input dictionary from a set of parser test files
220 function getFuzzInput( $filenames ) {
222 foreach( $filenames as $filename ) {
223 $contents = file_get_contents( $filename );
224 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
225 foreach ( $matches[1] as $match ) {
226 $dict .= $match . "\n";
233 * Get a memory usage breakdown
235 function getMemoryBreakdown() {
237 foreach ( $GLOBALS as $name => $value ) {
238 $memStats['$'.$name] = strlen( serialize( $value ) );
240 $classes = get_declared_classes();
241 foreach ( $classes as $class ) {
242 $rc = new ReflectionClass( $class );
243 $props = $rc->getStaticProperties();
244 $memStats[$class] = strlen( serialize( $props ) );
245 $methods = $rc->getMethods();
246 foreach ( $methods as $method ) {
247 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
250 $functions = get_defined_functions();
251 foreach ( $functions['user'] as $function ) {
252 $rf = new ReflectionFunction( $function );
253 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
264 * Run a series of tests listed in the given text files.
265 * Each test consists of a brief description, wikitext input,
266 * and the expected HTML output.
268 * Prints status updates on stdout and counts up the total
269 * number and percentage of passed tests.
271 * @param array of strings $filenames
272 * @return bool True if passed all tests, false if any tests failed.
274 public function runTestsFromFiles( $filenames ) {
275 $this->recorder->start();
276 $this->setupDatabase();
278 foreach( $filenames as $filename ) {
279 $ok = $this->runFile( $filename ) && $ok;
281 $this->teardownDatabase();
282 $this->recorder->report();
283 $this->recorder->end();
287 private function runFile( $filename ) {
288 $infile = fopen( $filename, 'rt' );
290 wfDie( "Couldn't open file '$filename'\n" );
293 $relative = wfRelativePath( $filename, $IP );
294 $this->showRunFile( $relative );
301 while( false !== ($line = fgets( $infile ) ) ) {
304 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
305 $section = strtolower( $matches[1] );
306 if( $section == 'endarticle') {
307 if( !isset( $data['text'] ) ) {
308 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
310 if( !isset( $data['article'] ) ) {
311 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
313 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
318 if( $section == 'endhooks' ) {
319 if( !isset( $data['hooks'] ) ) {
320 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
322 foreach( explode( "\n", $data['hooks'] ) as $line ) {
323 $line = trim( $line );
325 $this->requireHook( $line );
332 if( $section == 'endfunctionhooks' ) {
333 if( !isset( $data['functionhooks'] ) ) {
334 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
336 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
337 $line = trim( $line );
339 $this->requireFunctionHook( $line );
346 if( $section == 'end' ) {
347 if( !isset( $data['test'] ) ) {
348 wfDie( "'end' without 'test' at line $n of $filename\n" );
350 if( !isset( $data['input'] ) ) {
351 wfDie( "'end' without 'input' at line $n of $filename\n" );
353 if( !isset( $data['result'] ) ) {
354 wfDie( "'end' without 'result' at line $n of $filename\n" );
356 if( !isset( $data['options'] ) ) {
357 $data['options'] = '';
360 $data['options'] = $this->chomp( $data['options'] );
362 if (!isset( $data['config'] ) )
363 $data['config'] = '';
365 if ( (preg_match('/\\bdisabled\\b/i', $data['options'])
366 || !preg_match("/{$this->regex}/i", $data['test'])) && !$this->runDisabled ) {
372 if ( preg_match('/\\bmath\\b/i', $data['options']) && !$this->savedGlobals['wgUseTeX'] ) {
373 # don't run math tests if $wgUseTeX is set to false in LocalSettings
378 $result = $this->runTest(
379 $this->chomp( $data['test'] ),
380 $this->chomp( $data['input'] ),
381 $this->chomp( $data['result'] ),
382 $this->chomp( $data['options'] ),
383 $this->chomp( $data['config'] )
385 $ok = $ok && $result;
386 $this->recorder->record( $this->chomp( $data['test'] ), $result );
391 if ( isset ($data[$section] ) ) {
392 wfDie( "duplicate section '$section' at line $n of $filename\n" );
394 $data[$section] = '';
398 $data[$section] .= $line;
401 if ( $this->showProgress ) {
408 * Get a Parser object
410 function getParser() {
411 global $wgParserConf;
412 $class = $wgParserConf['class'];
413 $parser = new $class( $wgParserConf );
414 foreach( $this->hooks as $tag => $callback ) {
415 $parser->setHook( $tag, $callback );
417 foreach( $this->functionHooks as $tag => $bits ) {
418 list( $callback, $flags ) = $bits;
419 $parser->setFunctionHook( $tag, $callback, $flags );
421 wfRunHooks( 'ParserTestParser', array( &$parser ) );
426 * Run a given wikitext input through a freshly-constructed wiki parser,
427 * and compare the output against the expected results.
428 * Prints status and explanatory messages to stdout.
430 * @param string $input Wikitext to try rendering
431 * @param string $result Result to output
434 private function runTest( $desc, $input, $result, $opts, $config ) {
435 if( $this->showProgress ) {
436 $this->showTesting( $desc );
439 $opts = $this->parseOptions( $opts );
440 $this->setupGlobals($opts, $config);
443 $options = ParserOptions::newFromUser( $user );
446 if (isset( $opts['title'] ) ) {
447 $titleText = $opts['title'];
450 $titleText = 'Parser test';
453 $noxml = isset( $opts['noxml'] );
454 $local = isset( $opts['local'] );
455 $parser = $this->getParser();
456 $title = Title::newFromText( $titleText );
459 if( isset( $opts['pst'] ) ) {
460 $out = $parser->preSaveTransform( $input, $title, $user, $options );
461 } elseif( isset( $opts['msg'] ) ) {
462 $out = $parser->transformMsg( $input, $options );
463 } elseif( isset( $opts['section'] ) ) {
464 $section = $opts['section'];
465 $out = $parser->getSection( $input, $section );
466 } elseif( isset( $opts['replace'] ) ) {
467 $section = $opts['replace'][0];
468 $replace = $opts['replace'][1];
469 $out = $parser->replaceSection( $input, $section, $replace );
470 } elseif( isset( $opts['comment'] ) ) {
471 $linker = $user->getSkin();
472 $out = $linker->formatComment( $input, $title, $local );
474 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
475 $out = $output->getText();
477 if ( isset( $opts['showtitle'] ) ) {
478 $out = $output->getTitleText() . "\n$out";
480 if (isset( $opts['ill'] ) ) {
481 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
482 } elseif( isset( $opts['cat'] ) ) {
484 $wgOut->addCategoryLinks($output->getCategories());
485 $cats = $wgOut->getCategoryLinks();
486 if ( isset( $cats['normal'] ) ) {
487 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
493 $result = $this->tidy($result);
497 $this->teardownGlobals();
499 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
500 return $this->showSuccess( $desc );
502 return $this->showFailure( $desc, $result, $out );
508 * Use a regex to find out the value of an option
509 * @param $key name of option val to retrieve
510 * @param $opts Options array to look in
511 * @param $defaults Default value returned if not found
513 private static function getOptionValue( $key, $opts, $default ) {
514 $key = strtolower( $key );
515 if( isset( $opts[$key] ) ) {
522 private function parseOptions( $instring ) {
524 $lines = explode( "\n", $instring );
529 // foo=bar,"baz quux"
553 \[\[[^]]*\]\] # Link target
561 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
562 foreach( $matches as $bits ) {
563 $match = array_shift( $bits );
564 $key = strtolower( array_shift( $bits ) );
565 if( count( $bits ) == 0 ) {
567 } elseif( count( $bits ) == 1 ) {
568 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
571 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
578 private function cleanupOption( $opt ) {
579 if( substr( $opt, 0, 1 ) == '"' ) {
580 return substr( $opt, 1, -1 );
582 if( substr( $opt, 0, 2 ) == '[[' ) {
583 return substr( $opt, 2, -2 );
589 * Set up the global variables for a consistent environment for each test.
590 * Ideally this should replace the global configuration entirely.
592 private function setupGlobals($opts = '', $config = '') {
594 if( !isset( $this->uploadDir ) ) {
595 $this->uploadDir = $this->setupUploadDir();
598 # Find out values for some special options.
600 self::getOptionValue( 'language', $opts, 'en' );
602 self::getOptionValue( 'variant', $opts, false );
604 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
605 $linkHolderBatchSize =
606 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
609 'wgServer' => 'http://localhost',
610 'wgScript' => '/index.php',
611 'wgScriptPath' => '/',
612 'wgArticlePath' => '/wiki/$1',
613 'wgActionPaths' => array(),
614 'wgLocalFileRepo' => array(
615 'class' => 'LocalRepo',
617 'directory' => $this->uploadDir,
618 'url' => 'http://example.com/images',
620 'transformVia404' => false,
622 'wgEnableUploads' => true,
623 'wgStyleSheetPath' => '/skins',
624 'wgSitename' => 'MediaWiki',
625 'wgServerName' => 'Britney-Spears',
626 'wgLanguageCode' => $lang,
627 'wgContLanguageCode' => $lang,
628 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
629 'wgRawHtml' => isset( $opts['rawhtml'] ),
631 'wgContLang' => null,
632 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
633 'wgMaxTocLevel' => $maxtoclevel,
634 'wgCapitalLinks' => true,
635 'wgNoFollowLinks' => true,
636 'wgNoFollowDomainExceptions' => array(),
637 'wgThumbnailScriptPath' => false,
638 'wgUseImageResize' => false,
639 'wgUseTeX' => isset( $opts['math'] ),
640 'wgMathDirectory' => $this->uploadDir . '/math',
641 'wgLocaltimezone' => 'UTC',
642 'wgAllowExternalImages' => true,
643 'wgUseTidy' => false,
644 'wgDefaultLanguageVariant' => $variant,
645 'wgVariantArticlePath' => false,
646 'wgGroupPermissions' => array( '*' => array(
647 'createaccount' => true,
650 'createpage' => true,
651 'createtalk' => true,
653 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
654 'wgDefaultExternalStore' => array(),
655 'wgForeignFileRepos' => array(),
656 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
657 'wgExperimentalHtmlIds' => false,
658 'wgExternalLinkTarget' => false,
659 'wgAlwaysUseTidy' => false,
661 'wgWellFormedXml' => true,
662 'wgAllowMicrodataAttributes' => true,
666 $configLines = explode( "\n", $config );
668 foreach( $configLines as $line ) {
669 list( $var, $value ) = explode( '=', $line, 2 );
671 $settings[$var] = eval("return $value;" );
675 $this->savedGlobals = array();
676 foreach( $settings as $var => $val ) {
677 if( array_key_exists( $var, $GLOBALS ) ) {
678 $this->savedGlobals[$var] = $GLOBALS[$var];
680 $GLOBALS[$var] = $val;
682 $langObj = Language::factory( $lang );
683 $GLOBALS['wgLang'] = $langObj;
684 $GLOBALS['wgContLang'] = $langObj;
685 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
686 $GLOBALS['wgOut'] = new OutputPage;
688 MagicWord::clearCache();
691 $wgUser = new User();
695 * List of temporary tables to create, without prefix.
696 * Some of these probably aren't necessary.
698 private function listTables() {
700 $tables = array('user', 'page', 'page_restrictions',
701 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
702 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
703 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
704 'recentchanges', 'watchlist', 'math', 'interwiki',
705 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
706 'archive', 'user_groups', 'page_props', 'category'
709 if ($wgDBtype === 'mysql')
710 array_push( $tables, 'searchindex' );
712 // Allow extensions to add to the list of tables to duplicate;
713 // may be necessary if they hook into page save or other code
714 // which will require them while running tests.
715 wfRunHooks( 'ParserTestTables', array( &$tables ) );
721 * Set up a temporary set of wiki tables to work with for the tests.
722 * Currently this will only be done once per run, and any changes to
723 * the db will be visible to later tests in the run.
725 private function setupDatabase() {
726 global $wgDBprefix, $wgDBtype;
727 if ( $this->databaseSetupDone ) {
730 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
731 throw new MWException( 'setupDatabase should be called before setupGlobals' );
733 $this->databaseSetupDone = true;
734 $this->oldTablePrefix = $wgDBprefix;
736 # CREATE TEMPORARY TABLE breaks if there is more than one server
737 # FIXME: r40209 makes temporary tables break even with just one server
738 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
739 if ( true || wfGetLB()->getServerCount() != 1 ) {
740 $this->useTemporaryTables = false;
743 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
745 $db = wfGetDB( DB_MASTER );
746 $tables = $this->listTables();
748 foreach ( $tables as $tbl ) {
749 # Clean up from previous aborted run. So that table escaping
750 # works correctly across DB engines, we need to change the pre-
751 # fix back and forth so tableName() works right.
752 $this->changePrefix( $this->oldTablePrefix );
753 $oldTableName = $db->tableName( $tbl );
754 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
755 $newTableName = $db->tableName( $tbl );
757 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
758 $db->query( "DROP TABLE $newTableName" );
761 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
763 if ($wgDBtype == 'oracle')
764 $db->query('BEGIN FILL_WIKI_INFO; END;');
766 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
768 # Hack: insert a few Wikipedia in-project interwiki prefixes,
769 # for testing inter-language links
770 $db->insert( 'interwiki', array(
771 array( 'iw_prefix' => 'wikipedia',
772 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
774 array( 'iw_prefix' => 'meatball',
775 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
777 array( 'iw_prefix' => 'zh',
778 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
780 array( 'iw_prefix' => 'es',
781 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
783 array( 'iw_prefix' => 'fr',
784 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
786 array( 'iw_prefix' => 'ru',
787 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
792 if ($wgDBtype == 'oracle') {
793 # Insert 0 and 1 user_ids to prevent FK violations
796 $db->insert( 'user', array(
798 'user_name' => 'Anonymous') );
800 # Hack-on-Hack: Insert a test user to be able to insert an image
801 $db->insert( 'user', array(
803 'user_name' => 'Tester') );
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 # This image will be blacklisted in [[MediaWiki:Bad image list]]
824 $db->insert( 'image', array(
825 'img_name' => 'Bad.jpg',
827 'img_description' => 'zomgnotcensored',
829 'img_user_text' => 'WikiSysop',
830 'img_timestamp' => $db->timestamp( '20010115123500' ),
834 'img_media_type' => MEDIATYPE_BITMAP,
835 'img_major_mime' => "image",
836 'img_minor_mime' => "jpeg",
837 'img_metadata' => serialize( array() ),
840 # Update certain things in site_stats
841 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
843 # Reinitialise the LocalisationCache to match the database state
844 Language::getLocalisationCache()->unloadAll();
846 # Make a new message cache
847 global $wgMessageCache, $wgMemc;
848 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
852 * Change the table prefix on all open DB connections/
854 protected function changePrefix( $prefix ) {
856 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
857 $wgDBprefix = $prefix;
860 public function changeLBPrefix( $lb, $prefix ) {
861 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
864 public function changeDBPrefix( $db, $prefix ) {
865 $db->tablePrefix( $prefix );
868 private function teardownDatabase() {
869 global $wgDBprefix, $wgDBtype;
870 if ( !$this->databaseSetupDone ) {
873 $this->changePrefix( $this->oldTablePrefix );
874 $this->databaseSetupDone = false;
875 if ( $this->useTemporaryTables ) {
876 # Don't need to do anything
881 $tables = $this->listTables();
882 $db = wfGetDB( DB_MASTER );
883 foreach ( $tables as $table ) {
884 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
887 if ($wgDBtype == 'oracle')
888 $db->query('BEGIN FILL_WIKI_INFO; END;');
893 * Create a dummy uploads directory which will contain a couple
894 * of files in order to pass existence tests.
895 * @return string The directory
897 private function setupUploadDir() {
899 if ( $this->keepUploads ) {
900 $dir = wfTempDir() . '/mwParser-images';
901 if ( is_dir( $dir ) ) {
905 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
908 wfDebug( "Creating upload directory $dir\n" );
909 if ( file_exists( $dir ) ) {
910 wfDebug( "Already exists!\n" );
913 wfMkdirParents( $dir . '/3/3a' );
914 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
916 wfMkdirParents( $dir . '/0/09' );
917 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
922 * Restore default values and perform any necessary clean-up
923 * after each test runs.
925 private function teardownGlobals() {
926 RepoGroup::destroySingleton();
927 LinkCache::singleton()->clear();
928 foreach( $this->savedGlobals as $var => $val ) {
929 $GLOBALS[$var] = $val;
931 if( isset( $this->uploadDir ) ) {
932 $this->teardownUploadDir( $this->uploadDir );
933 unset( $this->uploadDir );
938 * Remove the dummy uploads directory
940 private function teardownUploadDir( $dir ) {
941 if ( $this->keepUploads ) {
945 // delete the files first, then the dirs.
948 "$dir/3/3a/Foobar.jpg",
949 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
950 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
951 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
952 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
956 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
966 "$dir/thumb/3/3a/Foobar.jpg",
983 * Delete the specified files, if they exist.
984 * @param array $files full paths to files to delete.
986 private static function deleteFiles( $files ) {
987 foreach( $files as $file ) {
988 if( file_exists( $file ) ) {
995 * Delete the specified directories, if they exist. Must be empty.
996 * @param array $dirs full paths to directories to delete.
998 private static function deleteDirs( $dirs ) {
999 foreach( $dirs as $dir ) {
1000 if( is_dir( $dir ) ) {
1007 * "Running test $desc..."
1009 protected function showTesting( $desc ) {
1010 print "Running test $desc... ";
1014 * Print a happy success message.
1016 * @param string $desc The test name
1019 protected function showSuccess( $desc ) {
1020 if( $this->showProgress ) {
1021 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1027 * Print a failure message and provide some explanatory output
1028 * about what went wrong if so configured.
1030 * @param string $desc The test name
1031 * @param string $result Expected HTML output
1032 * @param string $html Actual HTML output
1035 protected function showFailure( $desc, $result, $html ) {
1036 if( $this->showFailure ) {
1037 if( !$this->showProgress ) {
1038 # In quiet mode we didn't show the 'Testing' message before the
1039 # test, in case it succeeded. Show it now:
1040 $this->showTesting( $desc );
1042 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1043 if ( $this->showOutput ) {
1044 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1046 if( $this->showDiffs ) {
1047 print $this->quickDiff( $result, $html );
1048 if( !$this->wellFormed( $html ) ) {
1049 print "XML error: $this->mXmlError\n";
1057 * Run given strings through a diff and return the (colorized) output.
1058 * Requires writable /tmp directory and a 'diff' command in the PATH.
1060 * @param string $input
1061 * @param string $output
1062 * @param string $inFileTail Tailing for the input file name
1063 * @param string $outFileTail Tailing for the output file name
1066 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
1067 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1069 $infile = "$prefix-$inFileTail";
1070 $this->dumpToFile( $input, $infile );
1072 $outfile = "$prefix-$outFileTail";
1073 $this->dumpToFile( $output, $outfile );
1075 $diff = `diff -au $infile $outfile`;
1079 return $this->colorDiff( $diff );
1083 * Write the given string to a file, adding a final newline.
1085 * @param string $data
1086 * @param string $filename
1088 private function dumpToFile( $data, $filename ) {
1089 $file = fopen( $filename, "wt" );
1090 fwrite( $file, $data . "\n" );
1095 * Colorize unified diff output if set for ANSI color output.
1096 * Subtractions are colored blue, additions red.
1098 * @param string $text
1101 protected function colorDiff( $text ) {
1102 return preg_replace(
1103 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1104 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1105 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1110 * Show "Reading tests from ..."
1112 * @param String $path
1114 protected function showRunFile( $path ){
1115 print $this->term->color( 1 ) .
1116 "Reading tests from \"$path\"..." .
1117 $this->term->reset() .
1122 * Insert a temporary test article
1123 * @param string $name the title, including any prefix
1124 * @param string $text the article text
1125 * @param int $line the input line number, for reporting errors
1127 private function addArticle($name, $text, $line) {
1128 $this->setupGlobals();
1129 $title = Title::newFromText( $name );
1130 if ( is_null($title) ) {
1131 wfDie( "invalid title at line $line\n" );
1134 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1136 wfDie( "duplicate article at line $line\n" );
1139 $art = new Article($title);
1140 $art->insertNewArticle($text, '', false, false );
1142 $this->teardownGlobals();
1146 * Steal a callback function from the primary parser, save it for
1147 * application to our scary parser. If the hook is not installed,
1148 * die a painful dead to warn the others.
1149 * @param string $name
1151 private function requireHook( $name ) {
1153 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1154 if( isset( $wgParser->mTagHooks[$name] ) ) {
1155 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1157 wfDie( "This test suite requires the '$name' hook extension.\n" );
1162 * Steal a callback function from the primary parser, save it for
1163 * application to our scary parser. If the hook is not installed,
1164 * die a painful dead to warn the others.
1165 * @param string $name
1167 private function requireFunctionHook( $name ) {
1169 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1170 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1171 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1173 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1178 * Run the "tidy" command on text if the $wgUseTidy
1181 * @param string $text the text to tidy
1185 private function tidy( $text ) {
1188 $text = Parser::tidy($text);
1193 private function wellFormed( $text ) {
1195 Sanitizer::hackDocType() .
1200 $parser = xml_parser_create( "UTF-8" );
1202 # case folding violates XML standard, turn it off
1203 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1205 if( !xml_parse( $parser, $html, true ) ) {
1206 $err = xml_error_string( xml_get_error_code( $parser ) );
1207 $position = xml_get_current_byte_index( $parser );
1208 $fragment = $this->extractFragment( $html, $position );
1209 $this->mXmlError = "$err at byte $position:\n$fragment";
1210 xml_parser_free( $parser );
1213 xml_parser_free( $parser );
1217 private function extractFragment( $text, $position ) {
1218 $start = max( 0, $position - 10 );
1219 $before = $position - $start;
1221 $this->term->color( 34 ) .
1222 substr( $text, $start, $before ) .
1223 $this->term->color( 0 ) .
1224 $this->term->color( 31 ) .
1225 $this->term->color( 1 ) .
1226 substr( $text, $position, 1 ) .
1227 $this->term->color( 0 ) .
1228 $this->term->color( 34 ) .
1229 substr( $text, $position + 1, 9 ) .
1230 $this->term->color( 0 ) .
1232 $display = str_replace( "\n", ' ', $fragment );
1234 str_repeat( ' ', $before ) .
1235 $this->term->color( 31 ) .
1237 $this->term->color( 0 );
1238 return "$display\n$caret";
1242 class AnsiTermColorer {
1243 function __construct() {
1247 * Return ANSI terminal escape code for changing text attribs/color
1249 * @param string $color Semicolon-separated list of attribute/color codes
1252 public function color( $color ) {
1253 global $wgCommandLineDarkBg;
1254 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1255 return "\x1b[{$light}{$color}m";
1259 * Return ANSI terminal escape code for restoring default text attributes
1263 public function reset() {
1264 return $this->color( 0 );
1268 /* A colour-less terminal */
1269 class DummyTermColorer {
1270 public function color( $color ) {
1274 public function reset() {
1279 class TestRecorder {
1283 function __construct( $parent ) {
1284 $this->parent = $parent;
1285 $this->term = $parent->term;
1293 function record( $test, $result ) {
1295 $this->success += ($result ? 1 : 0);
1303 if( $this->total > 0 ) {
1304 $this->reportPercentage( $this->success, $this->total );
1306 wfDie( "No tests found.\n" );
1310 function reportPercentage( $success, $total ) {
1311 $ratio = wfPercent( 100 * $success / $total );
1312 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1313 if( $success == $total ) {
1314 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1316 $failed = $total - $success ;
1317 print $this->term->color( 31 ) . "$failed tests failed!";
1319 print $this->term->reset() . "\n";
1320 return ($success == $total);
1324 class DbTestPreviewer extends TestRecorder {
1325 protected $lb; ///< Database load balancer
1326 protected $db; ///< Database connection to the main DB
1327 protected $curRun; ///< run ID number for the current run
1328 protected $prevRun; ///< run ID number for the previous run, if any
1329 protected $results; ///< Result array
1332 * This should be called before the table prefix is changed
1334 function __construct( $parent ) {
1335 parent::__construct( $parent );
1336 $this->lb = wfGetLBFactory()->newMainLB();
1337 // This connection will have the wiki's table prefix, not parsertest_
1338 $this->db = $this->lb->getConnection( DB_MASTER );
1342 * Set up result recording; insert a record for the run with the date
1343 * and all that fun stuff
1346 global $wgDBtype, $wgDBprefix;
1349 if( ! $this->db->tableExists( 'testrun' )
1350 or ! $this->db->tableExists( 'testitem' ) )
1352 print "WARNING> `testrun` table not found in database.\n";
1353 $this->prevRun = false;
1355 // We'll make comparisons against the previous run later...
1356 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1358 $this->results = array();
1361 function record( $test, $result ) {
1362 parent::record( $test, $result );
1363 $this->results[$test] = $result;
1367 if( $this->prevRun ) {
1368 // f = fail, p = pass, n = nonexistent
1369 // codes show before then after
1371 'fp' => 'previously failing test(s) now PASSING! :)',
1372 'pn' => 'previously PASSING test(s) removed o_O',
1373 'np' => 'new PASSING test(s) :)',
1375 'pf' => 'previously passing test(s) now FAILING! :(',
1376 'fn' => 'previously FAILING test(s) removed O_o',
1377 'nf' => 'new FAILING test(s) :(',
1378 'ff' => 'still FAILING test(s) :(',
1381 $prevResults = array();
1383 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1384 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1385 foreach ( $res as $row ) {
1386 if ( !$this->parent->regex
1387 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1389 $prevResults[$row->ti_name] = $row->ti_success;
1393 $combined = array_keys( $this->results + $prevResults );
1395 # Determine breakdown by change type
1396 $breakdown = array();
1397 foreach ( $combined as $test ) {
1398 if ( !isset( $prevResults[$test] ) ) {
1400 } elseif ( $prevResults[$test] == 1 ) {
1402 } else /* if ( $prevResults[$test] == 0 )*/ {
1405 if ( !isset( $this->results[$test] ) ) {
1407 } elseif ( $this->results[$test] == 1 ) {
1409 } else /*if ( $this->results[$test] == 0 ) */ {
1412 $code = $before . $after;
1413 if ( isset( $table[$code] ) ) {
1414 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1419 foreach ( $table as $code => $label ) {
1420 if( !empty( $breakdown[$code] ) ) {
1421 $count = count($breakdown[$code]);
1422 printf( "\n%4d %s\n", $count, $label );
1423 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1424 print " * $differing_test_name [$statusInfo]\n";
1429 print "No previous test runs to compare against.\n";
1436 ** Returns a string giving information about when a test last had a status change.
1437 ** Could help to track down when regressions were introduced, as distinct from tests
1438 ** which have never passed (which are more change requests than regressions).
1440 private function getTestStatusInfo($testname, $after) {
1442 // If we're looking at a test that has just been removed, then say when it first appeared.
1443 if ( $after == 'n' ) {
1444 $changedRun = $this->db->selectField ( 'testitem',
1446 array( 'ti_name' => $testname ),
1448 $appear = $this->db->selectRow ( 'testrun',
1449 array( 'tr_date', 'tr_mw_version' ),
1450 array( 'tr_id' => $changedRun ),
1452 return "First recorded appearance: "
1453 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1454 . ", " . $appear->tr_mw_version;
1457 // Otherwise, this test has previous recorded results.
1458 // See when this test last had a different result to what we're seeing now.
1460 'ti_name' => $testname,
1461 'ti_success' => ($after == 'f' ? "1" : "0") );
1462 if ( $this->curRun ) {
1463 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1466 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1468 // If no record of ever having had a different result.
1469 if ( is_null ( $changedRun ) ) {
1470 if ($after == "f") {
1471 return "Has never passed";
1473 return "Has never failed";
1477 // Otherwise, we're looking at a test whose status has changed.
1478 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1479 // In this situation, give as much info as we can as to when it changed status.
1480 $pre = $this->db->selectRow ( 'testrun',
1481 array( 'tr_date', 'tr_mw_version' ),
1482 array( 'tr_id' => $changedRun ),
1484 $post = $this->db->selectRow ( 'testrun',
1485 array( 'tr_date', 'tr_mw_version' ),
1486 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1488 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1492 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1496 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1497 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1503 * Commit transaction and clean up for result recording
1506 $this->lb->commitMasterChanges();
1507 $this->lb->closeAll();
1513 class DbTestRecorder extends DbTestPreviewer {
1515 * Set up result recording; insert a record for the run with the date
1516 * and all that fun stuff
1519 global $wgDBtype, $wgDBprefix, $options;
1522 if( ! $this->db->tableExists( 'testrun' )
1523 or ! $this->db->tableExists( 'testitem' ) )
1525 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1526 if ($wgDBtype === 'postgres')
1527 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1528 elseif ($wgDBtype === 'oracle')
1529 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1531 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1532 echo "OK, resuming.\n";
1537 $this->db->insert( 'testrun',
1539 'tr_date' => $this->db->timestamp(),
1540 'tr_mw_version' => isset( $options['setversion'] ) ?
1541 $options['setversion'] : SpecialVersion::getVersion(),
1542 'tr_php_version' => phpversion(),
1543 'tr_db_version' => $this->db->getServerVersion(),
1544 'tr_uname' => php_uname()
1547 if ($wgDBtype === 'postgres')
1548 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1550 $this->curRun = $this->db->insertId();
1554 * Record an individual test item's success or failure to the db
1555 * @param string $test
1556 * @param bool $result
1558 function record( $test, $result ) {
1559 parent::record( $test, $result );
1560 $this->db->insert( 'testitem',
1562 'ti_run' => $this->curRun,
1564 'ti_success' => $result ? 1 : 0,
1570 class RemoteTestRecorder extends TestRecorder {
1573 $this->results = array();
1574 $this->ping( 'running' );
1577 function record( $test, $result ) {
1578 parent::record( $test, $result );
1579 $this->results[$test] = (bool)$result;
1583 $this->ping( 'complete', $this->results );
1588 * Inform a CodeReview instance that we've started or completed a test run...
1589 * @param $remote array: info on remote target
1590 * @param $status string: "running" - tell it we've started
1591 * "complete" - provide test results array
1592 * "abort" - something went horribly awry
1593 * @param $data array of test name => true/false
1595 function ping( $status, $results=false ) {
1596 global $wgParserTestRemote, $IP;
1598 $remote = $wgParserTestRemote;
1599 $revId = SpecialVersion::getSvnRevision( $IP );
1600 $jsonResults = json_encode( $results );
1603 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1607 // Generate a hash MAC to validate our credentials
1614 if( $status == "complete" ) {
1615 $message[] = $jsonResults;
1617 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1620 'action' => 'codetestupload',
1622 'repo' => $remote['repo'],
1623 'suite' => $remote['suite'],
1625 'status' => $status,
1628 if( $status == "complete" ) {
1629 $postData['results'] = $jsonResults;
1631 $response = $this->post( $remote['api-url'], $postData );
1633 if( $response === false ) {
1634 print "CodeReview info upload failed to reach server.\n";
1637 $responseData = json_decode( $response, true );
1638 if( !is_array( $responseData ) ) {
1639 print "CodeReview API response not recognized...\n";
1640 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1643 if( isset( $responseData['error'] ) ) {
1644 $code = $responseData['error']['code'];
1645 $info = $responseData['error']['info'];
1646 print "CodeReview info upload failed: $code $info\n";
1651 function post( $url, $data ) {
1652 return Http::post( $url, array( 'postData' => $data) );