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 if ( preg_match('/\\bmath\\b/i', $data['options']) && !$this->savedGlobals['wgUseTeX'] ) {
371 # don't run math tests if $wgUseTeX is set to false in LocalSettings
376 $result = $this->runTest(
377 $this->chomp( $data['test'] ),
378 $this->chomp( $data['input'] ),
379 $this->chomp( $data['result'] ),
380 $this->chomp( $data['options'] ),
381 $this->chomp( $data['config'] )
383 $ok = $ok && $result;
384 $this->recorder->record( $this->chomp( $data['test'] ), $result );
389 if ( isset ($data[$section] ) ) {
390 wfDie( "duplicate section '$section' at line $n of $filename\n" );
392 $data[$section] = '';
396 $data[$section] .= $line;
399 if ( $this->showProgress ) {
406 * Get a Parser object
408 function getParser() {
409 global $wgParserConf;
410 $class = $wgParserConf['class'];
411 $parser = new $class( $wgParserConf );
412 foreach( $this->hooks as $tag => $callback ) {
413 $parser->setHook( $tag, $callback );
415 foreach( $this->functionHooks as $tag => $bits ) {
416 list( $callback, $flags ) = $bits;
417 $parser->setFunctionHook( $tag, $callback, $flags );
419 wfRunHooks( 'ParserTestParser', array( &$parser ) );
424 * Run a given wikitext input through a freshly-constructed wiki parser,
425 * and compare the output against the expected results.
426 * Prints status and explanatory messages to stdout.
428 * @param string $input Wikitext to try rendering
429 * @param string $result Result to output
432 private function runTest( $desc, $input, $result, $opts, $config ) {
433 if( $this->showProgress ) {
434 $this->showTesting( $desc );
437 $opts = $this->parseOptions( $opts );
438 $this->setupGlobals($opts, $config);
441 $options = ParserOptions::newFromUser( $user );
443 if ( isset( $opts['math'] ) ) {
444 # XXX this should probably be done by the ParserOptions
445 $options->setUseTex(true);
449 if (isset( $opts['title'] ) ) {
450 $titleText = $opts['title'];
453 $titleText = 'Parser test';
456 $noxml = isset( $opts['noxml'] );
457 $local = isset( $opts['local'] );
458 $parser = $this->getParser();
459 $title = Title::newFromText( $titleText );
462 if( isset( $opts['pst'] ) ) {
463 $out = $parser->preSaveTransform( $input, $title, $user, $options );
464 } elseif( isset( $opts['msg'] ) ) {
465 $out = $parser->transformMsg( $input, $options );
466 } elseif( isset( $opts['section'] ) ) {
467 $section = $opts['section'];
468 $out = $parser->getSection( $input, $section );
469 } elseif( isset( $opts['replace'] ) ) {
470 $section = $opts['replace'][0];
471 $replace = $opts['replace'][1];
472 $out = $parser->replaceSection( $input, $section, $replace );
473 } elseif( isset( $opts['comment'] ) ) {
474 $linker = $user->getSkin();
475 $out = $linker->formatComment( $input, $title, $local );
477 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
478 $out = $output->getText();
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);
496 $this->teardownGlobals();
498 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
499 return $this->showSuccess( $desc );
501 return $this->showFailure( $desc, $result, $out );
507 * Use a regex to find out the value of an option
508 * @param $key name of option val to retrieve
509 * @param $opts Options array to look in
510 * @param $defaults Default value returned if not found
512 private static function getOptionValue( $key, $opts, $default ) {
513 $key = strtolower( $key );
514 if( isset( $opts[$key] ) ) {
521 private function parseOptions( $instring ) {
523 $lines = explode( "\n", $instring );
528 // foo=bar,"baz quux"
552 \[\[[^]]*\]\] # Link target
560 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
561 foreach( $matches as $bits ) {
562 $match = array_shift( $bits );
563 $key = strtolower( array_shift( $bits ) );
564 if( count( $bits ) == 0 ) {
566 } elseif( count( $bits ) == 1 ) {
567 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
570 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
577 private function cleanupOption( $opt ) {
578 if( substr( $opt, 0, 1 ) == '"' ) {
579 return substr( $opt, 1, -1 );
581 if( substr( $opt, 0, 2 ) == '[[' ) {
582 return substr( $opt, 2, -2 );
588 * Set up the global variables for a consistent environment for each test.
589 * Ideally this should replace the global configuration entirely.
591 private function setupGlobals($opts = '', $config = '') {
592 if( !isset( $this->uploadDir ) ) {
593 $this->uploadDir = $this->setupUploadDir();
596 # Find out values for some special options.
598 self::getOptionValue( 'language', $opts, 'en' );
600 self::getOptionValue( 'variant', $opts, false );
602 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
603 $linkHolderBatchSize =
604 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
607 'wgServer' => 'http://localhost',
608 'wgScript' => '/index.php',
609 'wgScriptPath' => '/',
610 'wgArticlePath' => '/wiki/$1',
611 'wgActionPaths' => array(),
612 'wgLocalFileRepo' => array(
613 'class' => 'LocalRepo',
615 'directory' => $this->uploadDir,
616 'url' => 'http://example.com/images',
618 'transformVia404' => false,
620 'wgEnableUploads' => true,
621 'wgStyleSheetPath' => '/skins',
622 'wgSitename' => 'MediaWiki',
623 'wgServerName' => 'Britney-Spears',
624 'wgLanguageCode' => $lang,
625 'wgContLanguageCode' => $lang,
626 'wgDBprefix' => 'parsertest_',
627 'wgRawHtml' => isset( $opts['rawhtml'] ),
629 'wgContLang' => null,
630 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
631 'wgMaxTocLevel' => $maxtoclevel,
632 'wgCapitalLinks' => true,
633 'wgNoFollowLinks' => true,
634 'wgNoFollowDomainExceptions' => array(),
635 'wgThumbnailScriptPath' => false,
637 'wgLocaltimezone' => 'UTC',
638 'wgAllowExternalImages' => true,
639 'wgUseTidy' => false,
640 'wgDefaultLanguageVariant' => $variant,
641 'wgVariantArticlePath' => false,
642 'wgGroupPermissions' => array( '*' => array(
643 'createaccount' => true,
646 'createpage' => true,
647 'createtalk' => true,
649 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
650 'wgDefaultExternalStore' => array(),
651 'wgForeignFileRepos' => array(),
652 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
653 'wgEnforceHtmlIds' => true,
654 'wgExternalLinkTarget' => false,
655 'wgAlwaysUseTidy' => false,
657 'wgWellFormedXml' => true,
661 $configLines = explode( "\n", $config );
663 foreach( $configLines as $line ) {
664 list( $var, $value ) = explode( '=', $line, 2 );
666 $settings[$var] = eval("return $value;" );
670 $this->savedGlobals = array();
671 foreach( $settings as $var => $val ) {
672 $this->savedGlobals[$var] = $GLOBALS[$var];
673 $GLOBALS[$var] = $val;
675 $langObj = Language::factory( $lang );
676 $GLOBALS['wgLang'] = $langObj;
677 $GLOBALS['wgContLang'] = $langObj;
678 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
679 $GLOBALS['wgOut'] = new OutputPage;
681 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
683 MagicWord::clearCache();
686 $wgUser = new User();
690 * List of temporary tables to create, without prefix.
691 * Some of these probably aren't necessary.
693 private function listTables() {
695 $tables = array('user', 'page', 'page_restrictions',
696 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
697 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
698 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
699 'recentchanges', 'watchlist', 'math', 'interwiki',
700 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
701 'archive', 'user_groups', 'page_props', 'category'
704 if ($wgDBtype === 'mysql')
705 array_push( $tables, 'searchindex' );
707 // Allow extensions to add to the list of tables to duplicate;
708 // may be necessary if they hook into page save or other code
709 // which will require them while running tests.
710 wfRunHooks( 'ParserTestTables', array( &$tables ) );
716 * Set up a temporary set of wiki tables to work with for the tests.
717 * Currently this will only be done once per run, and any changes to
718 * the db will be visible to later tests in the run.
720 private function setupDatabase() {
721 global $wgDBprefix, $wgDBtype;
722 if ( $this->databaseSetupDone ) {
725 if ( $wgDBprefix === 'parsertest_' ) {
726 throw new MWException( 'setupDatabase should be called before setupGlobals' );
728 $this->databaseSetupDone = true;
729 $this->oldTablePrefix = $wgDBprefix;
731 # CREATE TEMPORARY TABLE breaks if there is more than one server
732 # FIXME: r40209 makes temporary tables break even with just one server
733 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
734 if ( true || wfGetLB()->getServerCount() != 1 ) {
735 $this->useTemporaryTables = false;
738 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
740 $db = wfGetDB( DB_MASTER );
741 $tables = $this->listTables();
743 if ( !( $wgDBtype == 'mysql' && strcmp( $db->getServerVersion(), '4.1' ) < 0 ) ) {
744 # Database that supports CREATE TABLE ... LIKE
746 if( $wgDBtype == 'postgres' ) {
747 $def = 'INCLUDING DEFAULTS';
748 $temporary = 'TEMPORARY';
752 foreach ( $tables as $tbl ) {
753 # Clean up from previous aborted run. So that table escaping
754 # works correctly across DB engines, we need to change the pre-
755 # fix back and forth so tableName() works right.
756 $this->changePrefix( $this->oldTablePrefix );
757 $oldTableName = $db->tableName( $tbl );
758 $this->changePrefix( 'parsertest_' );
759 $newTableName = $db->tableName( $tbl );
761 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' ) {
762 $db->query( "DROP TABLE $newTableName" );
765 $db->query( "CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)" );
768 # Hack for MySQL versions < 4.1, which don't support
769 # "CREATE TABLE ... LIKE". Note that
770 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
771 # would not create the indexes we need....
773 # Note that we don't bother changing around the prefixes here be-
774 # cause we know we're using MySQL anyway.
775 foreach ($tables as $tbl) {
776 $oldTableName = $db->tableName( $tbl );
777 $res = $db->query("SHOW CREATE TABLE $oldTableName");
778 $row = $db->fetchRow($res);
780 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
781 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
782 if ($create === $create_tmp) {
783 # Couldn't do replacement
784 wfDie("could not create temporary table $tbl");
786 $db->query($create_tmp);
790 $this->changePrefix( 'parsertest_' );
792 # Hack: insert a few Wikipedia in-project interwiki prefixes,
793 # for testing inter-language links
794 $db->insert( 'interwiki', array(
795 array( 'iw_prefix' => 'wikipedia',
796 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
798 array( 'iw_prefix' => 'meatball',
799 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
801 array( 'iw_prefix' => 'zh',
802 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
804 array( 'iw_prefix' => 'es',
805 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
807 array( 'iw_prefix' => 'fr',
808 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
810 array( 'iw_prefix' => 'ru',
811 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
815 # Hack: Insert an image to work with
816 $db->insert( 'image', array(
817 'img_name' => 'Foobar.jpg',
819 'img_description' => 'Some lame file',
821 'img_user_text' => 'WikiSysop',
822 'img_timestamp' => $db->timestamp( '20010115123500' ),
826 'img_media_type' => MEDIATYPE_BITMAP,
827 'img_major_mime' => "image",
828 'img_minor_mime' => "jpeg",
829 'img_metadata' => serialize( array() ),
832 # Update certain things in site_stats
833 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
835 # Reinitialise the LocalisationCache to match the database state
836 Language::getLocalisationCache()->unloadAll();
840 * Change the table prefix on all open DB connections/
842 protected function changePrefix( $prefix ) {
844 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
845 $wgDBprefix = $prefix;
848 public function changeLBPrefix( $lb, $prefix ) {
849 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
852 public function changeDBPrefix( $db, $prefix ) {
853 $db->tablePrefix( $prefix );
856 private function teardownDatabase() {
858 if ( !$this->databaseSetupDone ) {
861 $this->changePrefix( $this->oldTablePrefix );
862 $this->databaseSetupDone = false;
863 if ( $this->useTemporaryTables ) {
864 # Don't need to do anything
869 $tables = $this->listTables();
870 $db = wfGetDB( DB_MASTER );
871 foreach ( $tables as $table ) {
872 $db->query( "DROP TABLE `parsertest_$table`" );
877 * Create a dummy uploads directory which will contain a couple
878 * of files in order to pass existence tests.
879 * @return string The directory
881 private function setupUploadDir() {
883 if ( $this->keepUploads ) {
884 $dir = wfTempDir() . '/mwParser-images';
885 if ( is_dir( $dir ) ) {
889 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
892 wfDebug( "Creating upload directory $dir\n" );
893 if ( file_exists( $dir ) ) {
894 wfDebug( "Already exists!\n" );
897 wfMkdirParents( $dir . '/3/3a' );
898 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
903 * Restore default values and perform any necessary clean-up
904 * after each test runs.
906 private function teardownGlobals() {
907 RepoGroup::destroySingleton();
908 LinkCache::singleton()->clear();
909 foreach( $this->savedGlobals as $var => $val ) {
910 $GLOBALS[$var] = $val;
912 if( isset( $this->uploadDir ) ) {
913 $this->teardownUploadDir( $this->uploadDir );
914 unset( $this->uploadDir );
919 * Remove the dummy uploads directory
921 private function teardownUploadDir( $dir ) {
922 if ( $this->keepUploads ) {
926 // delete the files first, then the dirs.
929 "$dir/3/3a/Foobar.jpg",
930 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
931 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
932 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
933 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
943 "$dir/thumb/3/3a/Foobar.jpg",
953 * Delete the specified files, if they exist.
954 * @param array $files full paths to files to delete.
956 private static function deleteFiles( $files ) {
957 foreach( $files as $file ) {
958 if( file_exists( $file ) ) {
965 * Delete the specified directories, if they exist. Must be empty.
966 * @param array $dirs full paths to directories to delete.
968 private static function deleteDirs( $dirs ) {
969 foreach( $dirs as $dir ) {
970 if( is_dir( $dir ) ) {
977 * "Running test $desc..."
979 protected function showTesting( $desc ) {
980 print "Running test $desc... ";
984 * Print a happy success message.
986 * @param string $desc The test name
989 protected function showSuccess( $desc ) {
990 if( $this->showProgress ) {
991 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
997 * Print a failure message and provide some explanatory output
998 * about what went wrong if so configured.
1000 * @param string $desc The test name
1001 * @param string $result Expected HTML output
1002 * @param string $html Actual HTML output
1005 protected function showFailure( $desc, $result, $html ) {
1006 if( $this->showFailure ) {
1007 if( !$this->showProgress ) {
1008 # In quiet mode we didn't show the 'Testing' message before the
1009 # test, in case it succeeded. Show it now:
1010 $this->showTesting( $desc );
1012 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1013 if ( $this->showOutput ) {
1014 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1016 if( $this->showDiffs ) {
1017 print $this->quickDiff( $result, $html );
1018 if( !$this->wellFormed( $html ) ) {
1019 print "XML error: $this->mXmlError\n";
1027 * Run given strings through a diff and return the (colorized) output.
1028 * Requires writable /tmp directory and a 'diff' command in the PATH.
1030 * @param string $input
1031 * @param string $output
1032 * @param string $inFileTail Tailing for the input file name
1033 * @param string $outFileTail Tailing for the output file name
1036 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
1037 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1039 $infile = "$prefix-$inFileTail";
1040 $this->dumpToFile( $input, $infile );
1042 $outfile = "$prefix-$outFileTail";
1043 $this->dumpToFile( $output, $outfile );
1045 $diff = `diff -au $infile $outfile`;
1049 return $this->colorDiff( $diff );
1053 * Write the given string to a file, adding a final newline.
1055 * @param string $data
1056 * @param string $filename
1058 private function dumpToFile( $data, $filename ) {
1059 $file = fopen( $filename, "wt" );
1060 fwrite( $file, $data . "\n" );
1065 * Colorize unified diff output if set for ANSI color output.
1066 * Subtractions are colored blue, additions red.
1068 * @param string $text
1071 protected function colorDiff( $text ) {
1072 return preg_replace(
1073 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1074 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1075 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1080 * Show "Reading tests from ..."
1082 * @param String $path
1084 protected function showRunFile( $path ){
1085 print $this->term->color( 1 ) .
1086 "Reading tests from \"$path\"..." .
1087 $this->term->reset() .
1092 * Insert a temporary test article
1093 * @param string $name the title, including any prefix
1094 * @param string $text the article text
1095 * @param int $line the input line number, for reporting errors
1097 private function addArticle($name, $text, $line) {
1098 $this->setupGlobals();
1099 $title = Title::newFromText( $name );
1100 if ( is_null($title) ) {
1101 wfDie( "invalid title at line $line\n" );
1104 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1106 wfDie( "duplicate article at line $line\n" );
1109 $art = new Article($title);
1110 $art->insertNewArticle($text, '', false, false );
1111 $this->teardownGlobals();
1115 * Steal a callback function from the primary parser, save it for
1116 * application to our scary parser. If the hook is not installed,
1117 * die a painful dead to warn the others.
1118 * @param string $name
1120 private function requireHook( $name ) {
1122 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1123 if( isset( $wgParser->mTagHooks[$name] ) ) {
1124 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1126 wfDie( "This test suite requires the '$name' hook extension.\n" );
1131 * Steal a callback function from the primary parser, save it for
1132 * application to our scary parser. If the hook is not installed,
1133 * die a painful dead to warn the others.
1134 * @param string $name
1136 private function requireFunctionHook( $name ) {
1138 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1139 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1140 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1142 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1147 * Run the "tidy" command on text if the $wgUseTidy
1150 * @param string $text the text to tidy
1154 private function tidy( $text ) {
1157 $text = Parser::tidy($text);
1162 private function wellFormed( $text ) {
1164 Sanitizer::hackDocType() .
1169 $parser = xml_parser_create( "UTF-8" );
1171 # case folding violates XML standard, turn it off
1172 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1174 if( !xml_parse( $parser, $html, true ) ) {
1175 $err = xml_error_string( xml_get_error_code( $parser ) );
1176 $position = xml_get_current_byte_index( $parser );
1177 $fragment = $this->extractFragment( $html, $position );
1178 $this->mXmlError = "$err at byte $position:\n$fragment";
1179 xml_parser_free( $parser );
1182 xml_parser_free( $parser );
1186 private function extractFragment( $text, $position ) {
1187 $start = max( 0, $position - 10 );
1188 $before = $position - $start;
1190 $this->term->color( 34 ) .
1191 substr( $text, $start, $before ) .
1192 $this->term->color( 0 ) .
1193 $this->term->color( 31 ) .
1194 $this->term->color( 1 ) .
1195 substr( $text, $position, 1 ) .
1196 $this->term->color( 0 ) .
1197 $this->term->color( 34 ) .
1198 substr( $text, $position + 1, 9 ) .
1199 $this->term->color( 0 ) .
1201 $display = str_replace( "\n", ' ', $fragment );
1203 str_repeat( ' ', $before ) .
1204 $this->term->color( 31 ) .
1206 $this->term->color( 0 );
1207 return "$display\n$caret";
1211 class AnsiTermColorer {
1212 function __construct() {
1216 * Return ANSI terminal escape code for changing text attribs/color
1218 * @param string $color Semicolon-separated list of attribute/color codes
1221 public function color( $color ) {
1222 global $wgCommandLineDarkBg;
1223 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1224 return "\x1b[{$light}{$color}m";
1228 * Return ANSI terminal escape code for restoring default text attributes
1232 public function reset() {
1233 return $this->color( 0 );
1237 /* A colour-less terminal */
1238 class DummyTermColorer {
1239 public function color( $color ) {
1243 public function reset() {
1248 class TestRecorder {
1252 function __construct( $parent ) {
1253 $this->parent = $parent;
1254 $this->term = $parent->term;
1262 function record( $test, $result ) {
1264 $this->success += ($result ? 1 : 0);
1272 if( $this->total > 0 ) {
1273 $this->reportPercentage( $this->success, $this->total );
1275 wfDie( "No tests found.\n" );
1279 function reportPercentage( $success, $total ) {
1280 $ratio = wfPercent( 100 * $success / $total );
1281 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1282 if( $success == $total ) {
1283 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1285 $failed = $total - $success ;
1286 print $this->term->color( 31 ) . "$failed tests failed!";
1288 print $this->term->reset() . "\n";
1289 return ($success == $total);
1293 class DbTestPreviewer extends TestRecorder {
1294 protected $lb; ///< Database load balancer
1295 protected $db; ///< Database connection to the main DB
1296 protected $curRun; ///< run ID number for the current run
1297 protected $prevRun; ///< run ID number for the previous run, if any
1298 protected $results; ///< Result array
1301 * This should be called before the table prefix is changed
1303 function __construct( $parent ) {
1304 parent::__construct( $parent );
1305 $this->lb = wfGetLBFactory()->newMainLB();
1306 // This connection will have the wiki's table prefix, not parsertest_
1307 $this->db = $this->lb->getConnection( DB_MASTER );
1311 * Set up result recording; insert a record for the run with the date
1312 * and all that fun stuff
1315 global $wgDBtype, $wgDBprefix;
1318 if( ! $this->db->tableExists( 'testrun' )
1319 or ! $this->db->tableExists( 'testitem' ) )
1321 print "WARNING> `testrun` table not found in database.\n";
1322 $this->prevRun = false;
1324 // We'll make comparisons against the previous run later...
1325 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1327 $this->results = array();
1330 function record( $test, $result ) {
1331 parent::record( $test, $result );
1332 $this->results[$test] = $result;
1336 if( $this->prevRun ) {
1337 // f = fail, p = pass, n = nonexistent
1338 // codes show before then after
1340 'fp' => 'previously failing test(s) now PASSING! :)',
1341 'pn' => 'previously PASSING test(s) removed o_O',
1342 'np' => 'new PASSING test(s) :)',
1344 'pf' => 'previously passing test(s) now FAILING! :(',
1345 'fn' => 'previously FAILING test(s) removed O_o',
1346 'nf' => 'new FAILING test(s) :(',
1347 'ff' => 'still FAILING test(s) :(',
1350 $prevResults = array();
1352 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1353 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1354 foreach ( $res as $row ) {
1355 if ( !$this->parent->regex
1356 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1358 $prevResults[$row->ti_name] = $row->ti_success;
1362 $combined = array_keys( $this->results + $prevResults );
1364 # Determine breakdown by change type
1365 $breakdown = array();
1366 foreach ( $combined as $test ) {
1367 if ( !isset( $prevResults[$test] ) ) {
1369 } elseif ( $prevResults[$test] == 1 ) {
1371 } else /* if ( $prevResults[$test] == 0 )*/ {
1374 if ( !isset( $this->results[$test] ) ) {
1376 } elseif ( $this->results[$test] == 1 ) {
1378 } else /*if ( $this->results[$test] == 0 ) */ {
1381 $code = $before . $after;
1382 if ( isset( $table[$code] ) ) {
1383 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1388 foreach ( $table as $code => $label ) {
1389 if( !empty( $breakdown[$code] ) ) {
1390 $count = count($breakdown[$code]);
1391 printf( "\n%4d %s\n", $count, $label );
1392 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1393 print " * $differing_test_name [$statusInfo]\n";
1398 print "No previous test runs to compare against.\n";
1405 ** Returns a string giving information about when a test last had a status change.
1406 ** Could help to track down when regressions were introduced, as distinct from tests
1407 ** which have never passed (which are more change requests than regressions).
1409 private function getTestStatusInfo($testname, $after) {
1411 // If we're looking at a test that has just been removed, then say when it first appeared.
1412 if ( $after == 'n' ) {
1413 $changedRun = $this->db->selectField ( 'testitem',
1415 array( 'ti_name' => $testname ),
1417 $appear = $this->db->selectRow ( 'testrun',
1418 array( 'tr_date', 'tr_mw_version' ),
1419 array( 'tr_id' => $changedRun ),
1421 return "First recorded appearance: "
1422 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1423 . ", " . $appear->tr_mw_version;
1426 // Otherwise, this test has previous recorded results.
1427 // See when this test last had a different result to what we're seeing now.
1429 'ti_name' => $testname,
1430 'ti_success' => ($after == 'f' ? "1" : "0") );
1431 if ( $this->curRun ) {
1432 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1435 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1437 // If no record of ever having had a different result.
1438 if ( is_null ( $changedRun ) ) {
1439 if ($after == "f") {
1440 return "Has never passed";
1442 return "Has never failed";
1446 // Otherwise, we're looking at a test whose status has changed.
1447 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1448 // In this situation, give as much info as we can as to when it changed status.
1449 $pre = $this->db->selectRow ( 'testrun',
1450 array( 'tr_date', 'tr_mw_version' ),
1451 array( 'tr_id' => $changedRun ),
1453 $post = $this->db->selectRow ( 'testrun',
1454 array( 'tr_date', 'tr_mw_version' ),
1455 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1457 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1461 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1465 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1466 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1472 * Commit transaction and clean up for result recording
1475 $this->lb->commitMasterChanges();
1476 $this->lb->closeAll();
1482 class DbTestRecorder extends DbTestPreviewer {
1484 * Set up result recording; insert a record for the run with the date
1485 * and all that fun stuff
1488 global $wgDBtype, $wgDBprefix, $options;
1491 if( ! $this->db->tableExists( 'testrun' )
1492 or ! $this->db->tableExists( 'testitem' ) )
1494 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1495 if ($wgDBtype === 'postgres')
1496 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1498 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1499 echo "OK, resuming.\n";
1504 $this->db->insert( 'testrun',
1506 'tr_date' => $this->db->timestamp(),
1507 'tr_mw_version' => isset( $options['setversion'] ) ?
1508 $options['setversion'] : SpecialVersion::getVersion(),
1509 'tr_php_version' => phpversion(),
1510 'tr_db_version' => $this->db->getServerVersion(),
1511 'tr_uname' => php_uname()
1514 if ($wgDBtype === 'postgres')
1515 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1517 $this->curRun = $this->db->insertId();
1521 * Record an individual test item's success or failure to the db
1522 * @param string $test
1523 * @param bool $result
1525 function record( $test, $result ) {
1526 parent::record( $test, $result );
1527 $this->db->insert( 'testitem',
1529 'ti_run' => $this->curRun,
1531 'ti_success' => $result ? 1 : 0,
1537 class RemoteTestRecorder extends TestRecorder {
1540 $this->results = array();
1541 $this->ping( 'running' );
1544 function record( $test, $result ) {
1545 parent::record( $test, $result );
1546 $this->results[$test] = (bool)$result;
1550 $this->ping( 'complete', $this->results );
1555 * Inform a CodeReview instance that we've started or completed a test run...
1556 * @param $remote array: info on remote target
1557 * @param $status string: "running" - tell it we've started
1558 * "complete" - provide test results array
1559 * "abort" - something went horribly awry
1560 * @param $data array of test name => true/false
1562 function ping( $status, $results=false ) {
1563 global $wgParserTestRemote, $IP;
1565 $remote = $wgParserTestRemote;
1566 $revId = SpecialVersion::getSvnRevision( $IP );
1567 $jsonResults = json_encode( $results );
1570 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1574 // Generate a hash MAC to validate our credentials
1581 if( $status == "complete" ) {
1582 $message[] = $jsonResults;
1584 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1587 'action' => 'codetestupload',
1589 'repo' => $remote['repo'],
1590 'suite' => $remote['suite'],
1592 'status' => $status,
1595 if( $status == "complete" ) {
1596 $postData['results'] = $jsonResults;
1598 $response = $this->post( $remote['api-url'], $postData );
1600 if( $response === false ) {
1601 print "CodeReview info upload failed to reach server.\n";
1604 $responseData = json_decode( $response, true );
1605 if( !is_array( $responseData ) ) {
1606 print "CodeReview API response not recognized...\n";
1607 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1610 if( isset( $responseData['error'] ) ) {
1611 $code = $responseData['error']['code'];
1612 $info = $responseData['error']['info'];
1613 print "CodeReview info upload failed: $code $info\n";
1618 function post( $url, $data ) {
1619 // @fixme: for whatever reason, I get a 417 fail when using CURL's multipart form submit.
1620 // If we do form URL encoding ourselves, though, it should work.
1621 return Http::post( $url, array( 'postdata' => wfArrayToCGI( $data ) ) );