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 );
445 if ( isset( $opts['math'] ) ) {
446 # XXX this should probably be done by the ParserOptions
447 $options->setUseTex(true);
451 if (isset( $opts['title'] ) ) {
452 $titleText = $opts['title'];
455 $titleText = 'Parser test';
458 $noxml = isset( $opts['noxml'] );
459 $local = isset( $opts['local'] );
460 $parser = $this->getParser();
461 $title = Title::newFromText( $titleText );
464 if( isset( $opts['pst'] ) ) {
465 $out = $parser->preSaveTransform( $input, $title, $user, $options );
466 } elseif( isset( $opts['msg'] ) ) {
467 $out = $parser->transformMsg( $input, $options );
468 } elseif( isset( $opts['section'] ) ) {
469 $section = $opts['section'];
470 $out = $parser->getSection( $input, $section );
471 } elseif( isset( $opts['replace'] ) ) {
472 $section = $opts['replace'][0];
473 $replace = $opts['replace'][1];
474 $out = $parser->replaceSection( $input, $section, $replace );
475 } elseif( isset( $opts['comment'] ) ) {
476 $linker = $user->getSkin();
477 $out = $linker->formatComment( $input, $title, $local );
479 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
480 $out = $output->getText();
482 if ( isset( $opts['showtitle'] ) ) {
483 $out = $output->getTitleText() . "\n$out";
485 if (isset( $opts['ill'] ) ) {
486 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
487 } elseif( isset( $opts['cat'] ) ) {
489 $wgOut->addCategoryLinks($output->getCategories());
490 $cats = $wgOut->getCategoryLinks();
491 if ( isset( $cats['normal'] ) ) {
492 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
498 $result = $this->tidy($result);
502 $this->teardownGlobals();
504 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
505 return $this->showSuccess( $desc );
507 return $this->showFailure( $desc, $result, $out );
513 * Use a regex to find out the value of an option
514 * @param $key name of option val to retrieve
515 * @param $opts Options array to look in
516 * @param $defaults Default value returned if not found
518 private static function getOptionValue( $key, $opts, $default ) {
519 $key = strtolower( $key );
520 if( isset( $opts[$key] ) ) {
527 private function parseOptions( $instring ) {
529 $lines = explode( "\n", $instring );
534 // foo=bar,"baz quux"
558 \[\[[^]]*\]\] # Link target
566 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
567 foreach( $matches as $bits ) {
568 $match = array_shift( $bits );
569 $key = strtolower( array_shift( $bits ) );
570 if( count( $bits ) == 0 ) {
572 } elseif( count( $bits ) == 1 ) {
573 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
576 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
583 private function cleanupOption( $opt ) {
584 if( substr( $opt, 0, 1 ) == '"' ) {
585 return substr( $opt, 1, -1 );
587 if( substr( $opt, 0, 2 ) == '[[' ) {
588 return substr( $opt, 2, -2 );
594 * Set up the global variables for a consistent environment for each test.
595 * Ideally this should replace the global configuration entirely.
597 private function setupGlobals($opts = '', $config = '') {
599 if( !isset( $this->uploadDir ) ) {
600 $this->uploadDir = $this->setupUploadDir();
603 # Find out values for some special options.
605 self::getOptionValue( 'language', $opts, 'en' );
607 self::getOptionValue( 'variant', $opts, false );
609 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
610 $linkHolderBatchSize =
611 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
614 'wgServer' => 'http://localhost',
615 'wgScript' => '/index.php',
616 'wgScriptPath' => '/',
617 'wgArticlePath' => '/wiki/$1',
618 'wgActionPaths' => array(),
619 'wgLocalFileRepo' => array(
620 'class' => 'LocalRepo',
622 'directory' => $this->uploadDir,
623 'url' => 'http://example.com/images',
625 'transformVia404' => false,
627 'wgEnableUploads' => true,
628 'wgStyleSheetPath' => '/skins',
629 'wgSitename' => 'MediaWiki',
630 'wgServerName' => 'Britney-Spears',
631 'wgLanguageCode' => $lang,
632 'wgContLanguageCode' => $lang,
633 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
634 'wgRawHtml' => isset( $opts['rawhtml'] ),
636 'wgContLang' => null,
637 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
638 'wgMaxTocLevel' => $maxtoclevel,
639 'wgCapitalLinks' => true,
640 'wgNoFollowLinks' => true,
641 'wgNoFollowDomainExceptions' => array(),
642 'wgThumbnailScriptPath' => false,
643 'wgUseImageResize' => false,
645 'wgLocaltimezone' => 'UTC',
646 'wgAllowExternalImages' => true,
647 'wgUseTidy' => false,
648 'wgDefaultLanguageVariant' => $variant,
649 'wgVariantArticlePath' => false,
650 'wgGroupPermissions' => array( '*' => array(
651 'createaccount' => true,
654 'createpage' => true,
655 'createtalk' => true,
657 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
658 'wgDefaultExternalStore' => array(),
659 'wgForeignFileRepos' => array(),
660 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
661 'wgExperimentalHtmlIds' => false,
662 'wgExternalLinkTarget' => false,
663 'wgAlwaysUseTidy' => false,
665 'wgWellFormedXml' => true,
666 'wgAllowMicrodataAttributes' => true,
670 $configLines = explode( "\n", $config );
672 foreach( $configLines as $line ) {
673 list( $var, $value ) = explode( '=', $line, 2 );
675 $settings[$var] = eval("return $value;" );
679 $this->savedGlobals = array();
680 foreach( $settings as $var => $val ) {
681 if( array_key_exists( $var, $GLOBALS ) ) {
682 $this->savedGlobals[$var] = $GLOBALS[$var];
684 $GLOBALS[$var] = $val;
686 $langObj = Language::factory( $lang );
687 $GLOBALS['wgLang'] = $langObj;
688 $GLOBALS['wgContLang'] = $langObj;
689 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
690 $GLOBALS['wgOut'] = new OutputPage;
692 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
694 MagicWord::clearCache();
697 $wgUser = new User();
701 * List of temporary tables to create, without prefix.
702 * Some of these probably aren't necessary.
704 private function listTables() {
706 $tables = array('user', 'page', 'page_restrictions',
707 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
708 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
709 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
710 'recentchanges', 'watchlist', 'math', 'interwiki',
711 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
712 'archive', 'user_groups', 'page_props', 'category'
715 if ($wgDBtype === 'mysql')
716 array_push( $tables, 'searchindex' );
718 // Allow extensions to add to the list of tables to duplicate;
719 // may be necessary if they hook into page save or other code
720 // which will require them while running tests.
721 wfRunHooks( 'ParserTestTables', array( &$tables ) );
727 * Set up a temporary set of wiki tables to work with for the tests.
728 * Currently this will only be done once per run, and any changes to
729 * the db will be visible to later tests in the run.
731 private function setupDatabase() {
732 global $wgDBprefix, $wgDBtype;
733 if ( $this->databaseSetupDone ) {
736 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
737 throw new MWException( 'setupDatabase should be called before setupGlobals' );
739 $this->databaseSetupDone = true;
740 $this->oldTablePrefix = $wgDBprefix;
742 # CREATE TEMPORARY TABLE breaks if there is more than one server
743 # FIXME: r40209 makes temporary tables break even with just one server
744 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
745 if ( true || wfGetLB()->getServerCount() != 1 ) {
746 $this->useTemporaryTables = false;
749 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
751 $db = wfGetDB( DB_MASTER );
752 $tables = $this->listTables();
754 foreach ( $tables as $tbl ) {
755 # Clean up from previous aborted run. So that table escaping
756 # works correctly across DB engines, we need to change the pre-
757 # fix back and forth so tableName() works right.
758 $this->changePrefix( $this->oldTablePrefix );
759 $oldTableName = $db->tableName( $tbl );
760 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
761 $newTableName = $db->tableName( $tbl );
763 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
764 $db->query( "DROP TABLE $newTableName" );
767 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
769 if ($wgDBtype == 'oracle')
770 $db->query('BEGIN FILL_WIKI_INFO; END;');
772 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
774 # Hack: insert a few Wikipedia in-project interwiki prefixes,
775 # for testing inter-language links
776 $db->insert( 'interwiki', array(
777 array( 'iw_prefix' => 'wikipedia',
778 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
780 array( 'iw_prefix' => 'meatball',
781 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
783 array( 'iw_prefix' => 'zh',
784 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
786 array( 'iw_prefix' => 'es',
787 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
789 array( 'iw_prefix' => 'fr',
790 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
792 array( 'iw_prefix' => 'ru',
793 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
798 if ($wgDBtype == 'oracle') {
799 # Insert 0 and 1 user_ids to prevent FK violations
802 $db->insert( 'user', array(
804 'user_name' => 'Anonymous') );
806 # Hack-on-Hack: Insert a test user to be able to insert an image
807 $db->insert( 'user', array(
809 'user_name' => 'Tester') );
812 # Hack: Insert an image to work with
813 $db->insert( 'image', array(
814 'img_name' => 'Foobar.jpg',
816 'img_description' => 'Some lame file',
818 'img_user_text' => 'WikiSysop',
819 'img_timestamp' => $db->timestamp( '20010115123500' ),
823 'img_media_type' => MEDIATYPE_BITMAP,
824 'img_major_mime' => "image",
825 'img_minor_mime' => "jpeg",
826 'img_metadata' => serialize( array() ),
829 # This image will be blacklisted in [[MediaWiki:Bad image list]]
830 $db->insert( 'image', array(
831 'img_name' => 'Bad.jpg',
833 'img_description' => 'zomgnotcensored',
835 'img_user_text' => 'WikiSysop',
836 'img_timestamp' => $db->timestamp( '20010115123500' ),
840 'img_media_type' => MEDIATYPE_BITMAP,
841 'img_major_mime' => "image",
842 'img_minor_mime' => "jpeg",
843 'img_metadata' => serialize( array() ),
846 # Update certain things in site_stats
847 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
849 # Reinitialise the LocalisationCache to match the database state
850 Language::getLocalisationCache()->unloadAll();
854 * Change the table prefix on all open DB connections/
856 protected function changePrefix( $prefix ) {
858 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
859 $wgDBprefix = $prefix;
862 public function changeLBPrefix( $lb, $prefix ) {
863 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
866 public function changeDBPrefix( $db, $prefix ) {
867 $db->tablePrefix( $prefix );
870 private function teardownDatabase() {
871 global $wgDBprefix, $wgDBtype;
872 if ( !$this->databaseSetupDone ) {
875 $this->changePrefix( $this->oldTablePrefix );
876 $this->databaseSetupDone = false;
877 if ( $this->useTemporaryTables ) {
878 # Don't need to do anything
883 $tables = $this->listTables();
884 $db = wfGetDB( DB_MASTER );
885 foreach ( $tables as $table ) {
886 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
889 if ($wgDBtype == 'oracle')
890 $db->query('BEGIN FILL_WIKI_INFO; END;');
895 * Create a dummy uploads directory which will contain a couple
896 * of files in order to pass existence tests.
897 * @return string The directory
899 private function setupUploadDir() {
901 if ( $this->keepUploads ) {
902 $dir = wfTempDir() . '/mwParser-images';
903 if ( is_dir( $dir ) ) {
907 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
910 wfDebug( "Creating upload directory $dir\n" );
911 if ( file_exists( $dir ) ) {
912 wfDebug( "Already exists!\n" );
915 wfMkdirParents( $dir . '/3/3a' );
916 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
918 wfMkdirParents( $dir . '/0/09' );
919 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
924 * Restore default values and perform any necessary clean-up
925 * after each test runs.
927 private function teardownGlobals() {
928 RepoGroup::destroySingleton();
929 LinkCache::singleton()->clear();
930 foreach( $this->savedGlobals as $var => $val ) {
931 $GLOBALS[$var] = $val;
933 if( isset( $this->uploadDir ) ) {
934 $this->teardownUploadDir( $this->uploadDir );
935 unset( $this->uploadDir );
940 * Remove the dummy uploads directory
942 private function teardownUploadDir( $dir ) {
943 if ( $this->keepUploads ) {
947 // delete the files first, then the dirs.
950 "$dir/3/3a/Foobar.jpg",
951 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
952 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
953 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
954 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
966 "$dir/thumb/3/3a/Foobar.jpg",
980 * Delete the specified files, if they exist.
981 * @param array $files full paths to files to delete.
983 private static function deleteFiles( $files ) {
984 foreach( $files as $file ) {
985 if( file_exists( $file ) ) {
992 * Delete the specified directories, if they exist. Must be empty.
993 * @param array $dirs full paths to directories to delete.
995 private static function deleteDirs( $dirs ) {
996 foreach( $dirs as $dir ) {
997 if( is_dir( $dir ) ) {
1004 * "Running test $desc..."
1006 protected function showTesting( $desc ) {
1007 print "Running test $desc... ";
1011 * Print a happy success message.
1013 * @param string $desc The test name
1016 protected function showSuccess( $desc ) {
1017 if( $this->showProgress ) {
1018 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1024 * Print a failure message and provide some explanatory output
1025 * about what went wrong if so configured.
1027 * @param string $desc The test name
1028 * @param string $result Expected HTML output
1029 * @param string $html Actual HTML output
1032 protected function showFailure( $desc, $result, $html ) {
1033 if( $this->showFailure ) {
1034 if( !$this->showProgress ) {
1035 # In quiet mode we didn't show the 'Testing' message before the
1036 # test, in case it succeeded. Show it now:
1037 $this->showTesting( $desc );
1039 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1040 if ( $this->showOutput ) {
1041 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1043 if( $this->showDiffs ) {
1044 print $this->quickDiff( $result, $html );
1045 if( !$this->wellFormed( $html ) ) {
1046 print "XML error: $this->mXmlError\n";
1054 * Run given strings through a diff and return the (colorized) output.
1055 * Requires writable /tmp directory and a 'diff' command in the PATH.
1057 * @param string $input
1058 * @param string $output
1059 * @param string $inFileTail Tailing for the input file name
1060 * @param string $outFileTail Tailing for the output file name
1063 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
1064 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1066 $infile = "$prefix-$inFileTail";
1067 $this->dumpToFile( $input, $infile );
1069 $outfile = "$prefix-$outFileTail";
1070 $this->dumpToFile( $output, $outfile );
1072 $diff = `diff -au $infile $outfile`;
1076 return $this->colorDiff( $diff );
1080 * Write the given string to a file, adding a final newline.
1082 * @param string $data
1083 * @param string $filename
1085 private function dumpToFile( $data, $filename ) {
1086 $file = fopen( $filename, "wt" );
1087 fwrite( $file, $data . "\n" );
1092 * Colorize unified diff output if set for ANSI color output.
1093 * Subtractions are colored blue, additions red.
1095 * @param string $text
1098 protected function colorDiff( $text ) {
1099 return preg_replace(
1100 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1101 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1102 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1107 * Show "Reading tests from ..."
1109 * @param String $path
1111 protected function showRunFile( $path ){
1112 print $this->term->color( 1 ) .
1113 "Reading tests from \"$path\"..." .
1114 $this->term->reset() .
1119 * Insert a temporary test article
1120 * @param string $name the title, including any prefix
1121 * @param string $text the article text
1122 * @param int $line the input line number, for reporting errors
1124 private function addArticle($name, $text, $line) {
1125 global $wgMessageCache;
1126 $this->setupGlobals();
1127 $title = Title::newFromText( $name );
1128 if ( is_null($title) ) {
1129 wfDie( "invalid title at line $line\n" );
1132 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1134 wfDie( "duplicate article at line $line\n" );
1137 $art = new Article($title);
1138 $art->insertNewArticle($text, '', false, false );
1140 $this->teardownGlobals();
1144 * Steal a callback function from the primary parser, save it for
1145 * application to our scary parser. If the hook is not installed,
1146 * die a painful dead to warn the others.
1147 * @param string $name
1149 private function requireHook( $name ) {
1151 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1152 if( isset( $wgParser->mTagHooks[$name] ) ) {
1153 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1155 wfDie( "This test suite requires the '$name' hook extension.\n" );
1160 * Steal a callback function from the primary parser, save it for
1161 * application to our scary parser. If the hook is not installed,
1162 * die a painful dead to warn the others.
1163 * @param string $name
1165 private function requireFunctionHook( $name ) {
1167 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1168 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1169 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1171 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1176 * Run the "tidy" command on text if the $wgUseTidy
1179 * @param string $text the text to tidy
1183 private function tidy( $text ) {
1186 $text = Parser::tidy($text);
1191 private function wellFormed( $text ) {
1193 Sanitizer::hackDocType() .
1198 $parser = xml_parser_create( "UTF-8" );
1200 # case folding violates XML standard, turn it off
1201 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1203 if( !xml_parse( $parser, $html, true ) ) {
1204 $err = xml_error_string( xml_get_error_code( $parser ) );
1205 $position = xml_get_current_byte_index( $parser );
1206 $fragment = $this->extractFragment( $html, $position );
1207 $this->mXmlError = "$err at byte $position:\n$fragment";
1208 xml_parser_free( $parser );
1211 xml_parser_free( $parser );
1215 private function extractFragment( $text, $position ) {
1216 $start = max( 0, $position - 10 );
1217 $before = $position - $start;
1219 $this->term->color( 34 ) .
1220 substr( $text, $start, $before ) .
1221 $this->term->color( 0 ) .
1222 $this->term->color( 31 ) .
1223 $this->term->color( 1 ) .
1224 substr( $text, $position, 1 ) .
1225 $this->term->color( 0 ) .
1226 $this->term->color( 34 ) .
1227 substr( $text, $position + 1, 9 ) .
1228 $this->term->color( 0 ) .
1230 $display = str_replace( "\n", ' ', $fragment );
1232 str_repeat( ' ', $before ) .
1233 $this->term->color( 31 ) .
1235 $this->term->color( 0 );
1236 return "$display\n$caret";
1240 class AnsiTermColorer {
1241 function __construct() {
1245 * Return ANSI terminal escape code for changing text attribs/color
1247 * @param string $color Semicolon-separated list of attribute/color codes
1250 public function color( $color ) {
1251 global $wgCommandLineDarkBg;
1252 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1253 return "\x1b[{$light}{$color}m";
1257 * Return ANSI terminal escape code for restoring default text attributes
1261 public function reset() {
1262 return $this->color( 0 );
1266 /* A colour-less terminal */
1267 class DummyTermColorer {
1268 public function color( $color ) {
1272 public function reset() {
1277 class TestRecorder {
1281 function __construct( $parent ) {
1282 $this->parent = $parent;
1283 $this->term = $parent->term;
1291 function record( $test, $result ) {
1293 $this->success += ($result ? 1 : 0);
1301 if( $this->total > 0 ) {
1302 $this->reportPercentage( $this->success, $this->total );
1304 wfDie( "No tests found.\n" );
1308 function reportPercentage( $success, $total ) {
1309 $ratio = wfPercent( 100 * $success / $total );
1310 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1311 if( $success == $total ) {
1312 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1314 $failed = $total - $success ;
1315 print $this->term->color( 31 ) . "$failed tests failed!";
1317 print $this->term->reset() . "\n";
1318 return ($success == $total);
1322 class DbTestPreviewer extends TestRecorder {
1323 protected $lb; ///< Database load balancer
1324 protected $db; ///< Database connection to the main DB
1325 protected $curRun; ///< run ID number for the current run
1326 protected $prevRun; ///< run ID number for the previous run, if any
1327 protected $results; ///< Result array
1330 * This should be called before the table prefix is changed
1332 function __construct( $parent ) {
1333 parent::__construct( $parent );
1334 $this->lb = wfGetLBFactory()->newMainLB();
1335 // This connection will have the wiki's table prefix, not parsertest_
1336 $this->db = $this->lb->getConnection( DB_MASTER );
1340 * Set up result recording; insert a record for the run with the date
1341 * and all that fun stuff
1344 global $wgDBtype, $wgDBprefix;
1347 if( ! $this->db->tableExists( 'testrun' )
1348 or ! $this->db->tableExists( 'testitem' ) )
1350 print "WARNING> `testrun` table not found in database.\n";
1351 $this->prevRun = false;
1353 // We'll make comparisons against the previous run later...
1354 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1356 $this->results = array();
1359 function record( $test, $result ) {
1360 parent::record( $test, $result );
1361 $this->results[$test] = $result;
1365 if( $this->prevRun ) {
1366 // f = fail, p = pass, n = nonexistent
1367 // codes show before then after
1369 'fp' => 'previously failing test(s) now PASSING! :)',
1370 'pn' => 'previously PASSING test(s) removed o_O',
1371 'np' => 'new PASSING test(s) :)',
1373 'pf' => 'previously passing test(s) now FAILING! :(',
1374 'fn' => 'previously FAILING test(s) removed O_o',
1375 'nf' => 'new FAILING test(s) :(',
1376 'ff' => 'still FAILING test(s) :(',
1379 $prevResults = array();
1381 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1382 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1383 foreach ( $res as $row ) {
1384 if ( !$this->parent->regex
1385 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1387 $prevResults[$row->ti_name] = $row->ti_success;
1391 $combined = array_keys( $this->results + $prevResults );
1393 # Determine breakdown by change type
1394 $breakdown = array();
1395 foreach ( $combined as $test ) {
1396 if ( !isset( $prevResults[$test] ) ) {
1398 } elseif ( $prevResults[$test] == 1 ) {
1400 } else /* if ( $prevResults[$test] == 0 )*/ {
1403 if ( !isset( $this->results[$test] ) ) {
1405 } elseif ( $this->results[$test] == 1 ) {
1407 } else /*if ( $this->results[$test] == 0 ) */ {
1410 $code = $before . $after;
1411 if ( isset( $table[$code] ) ) {
1412 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1417 foreach ( $table as $code => $label ) {
1418 if( !empty( $breakdown[$code] ) ) {
1419 $count = count($breakdown[$code]);
1420 printf( "\n%4d %s\n", $count, $label );
1421 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1422 print " * $differing_test_name [$statusInfo]\n";
1427 print "No previous test runs to compare against.\n";
1434 ** Returns a string giving information about when a test last had a status change.
1435 ** Could help to track down when regressions were introduced, as distinct from tests
1436 ** which have never passed (which are more change requests than regressions).
1438 private function getTestStatusInfo($testname, $after) {
1440 // If we're looking at a test that has just been removed, then say when it first appeared.
1441 if ( $after == 'n' ) {
1442 $changedRun = $this->db->selectField ( 'testitem',
1444 array( 'ti_name' => $testname ),
1446 $appear = $this->db->selectRow ( 'testrun',
1447 array( 'tr_date', 'tr_mw_version' ),
1448 array( 'tr_id' => $changedRun ),
1450 return "First recorded appearance: "
1451 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1452 . ", " . $appear->tr_mw_version;
1455 // Otherwise, this test has previous recorded results.
1456 // See when this test last had a different result to what we're seeing now.
1458 'ti_name' => $testname,
1459 'ti_success' => ($after == 'f' ? "1" : "0") );
1460 if ( $this->curRun ) {
1461 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1464 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1466 // If no record of ever having had a different result.
1467 if ( is_null ( $changedRun ) ) {
1468 if ($after == "f") {
1469 return "Has never passed";
1471 return "Has never failed";
1475 // Otherwise, we're looking at a test whose status has changed.
1476 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1477 // In this situation, give as much info as we can as to when it changed status.
1478 $pre = $this->db->selectRow ( 'testrun',
1479 array( 'tr_date', 'tr_mw_version' ),
1480 array( 'tr_id' => $changedRun ),
1482 $post = $this->db->selectRow ( 'testrun',
1483 array( 'tr_date', 'tr_mw_version' ),
1484 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1486 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1490 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1494 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1495 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1501 * Commit transaction and clean up for result recording
1504 $this->lb->commitMasterChanges();
1505 $this->lb->closeAll();
1511 class DbTestRecorder extends DbTestPreviewer {
1513 * Set up result recording; insert a record for the run with the date
1514 * and all that fun stuff
1517 global $wgDBtype, $wgDBprefix, $options;
1520 if( ! $this->db->tableExists( 'testrun' )
1521 or ! $this->db->tableExists( 'testitem' ) )
1523 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1524 if ($wgDBtype === 'postgres')
1525 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1526 elseif ($wgDBtype === 'oracle')
1527 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1529 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1530 echo "OK, resuming.\n";
1535 $this->db->insert( 'testrun',
1537 'tr_date' => $this->db->timestamp(),
1538 'tr_mw_version' => isset( $options['setversion'] ) ?
1539 $options['setversion'] : SpecialVersion::getVersion(),
1540 'tr_php_version' => phpversion(),
1541 'tr_db_version' => $this->db->getServerVersion(),
1542 'tr_uname' => php_uname()
1545 if ($wgDBtype === 'postgres')
1546 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1548 $this->curRun = $this->db->insertId();
1552 * Record an individual test item's success or failure to the db
1553 * @param string $test
1554 * @param bool $result
1556 function record( $test, $result ) {
1557 parent::record( $test, $result );
1558 $this->db->insert( 'testitem',
1560 'ti_run' => $this->curRun,
1562 'ti_success' => $result ? 1 : 0,
1568 class RemoteTestRecorder extends TestRecorder {
1571 $this->results = array();
1572 $this->ping( 'running' );
1575 function record( $test, $result ) {
1576 parent::record( $test, $result );
1577 $this->results[$test] = (bool)$result;
1581 $this->ping( 'complete', $this->results );
1586 * Inform a CodeReview instance that we've started or completed a test run...
1587 * @param $remote array: info on remote target
1588 * @param $status string: "running" - tell it we've started
1589 * "complete" - provide test results array
1590 * "abort" - something went horribly awry
1591 * @param $data array of test name => true/false
1593 function ping( $status, $results=false ) {
1594 global $wgParserTestRemote, $IP;
1596 $remote = $wgParserTestRemote;
1597 $revId = SpecialVersion::getSvnRevision( $IP );
1598 $jsonResults = json_encode( $results );
1601 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1605 // Generate a hash MAC to validate our credentials
1612 if( $status == "complete" ) {
1613 $message[] = $jsonResults;
1615 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1618 'action' => 'codetestupload',
1620 'repo' => $remote['repo'],
1621 'suite' => $remote['suite'],
1623 'status' => $status,
1626 if( $status == "complete" ) {
1627 $postData['results'] = $jsonResults;
1629 $response = $this->post( $remote['api-url'], $postData );
1631 if( $response === false ) {
1632 print "CodeReview info upload failed to reach server.\n";
1635 $responseData = json_decode( $response, true );
1636 if( !is_array( $responseData ) ) {
1637 print "CodeReview API response not recognized...\n";
1638 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1641 if( isset( $responseData['error'] ) ) {
1642 $code = $responseData['error']['code'];
1643 $info = $responseData['error']['info'];
1644 print "CodeReview info upload failed: $code $info\n";
1649 function post( $url, $data ) {
1650 return Http::post( $url, array( 'postData' => $data) );