2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @ingroup Maintenance
28 $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 );
123 } elseif( class_exists( 'PHPUnitTestRecorder' ) ) {
124 $this->recorder = new PHPUnitTestRecorder( $this );
126 $this->recorder = new TestRecorder( $this );
128 $this->keepUploads = isset( $options['keep-uploads'] );
130 if ( isset( $options['seed'] ) ) {
131 $this->fuzzSeed = intval( $options['seed'] ) - 1;
134 $this->runDisabled = isset( $options['run-disabled'] );
136 $this->hooks = array();
137 $this->functionHooks = array();
141 * Remove last character if it is a newline
143 public function chomp($s) {
144 if (substr($s, -1) === "\n") {
145 return substr($s, 0, -1);
153 * Run a fuzz test series
154 * Draw input from a set of test files
156 function fuzzTest( $filenames ) {
157 $dict = $this->getFuzzInput( $filenames );
158 $dictSize = strlen( $dict );
159 $logMaxLength = log( $this->maxFuzzTestLength );
160 $this->setupDatabase();
161 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
166 $opts = ParserOptions::newFromUser( $user );
167 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
170 // Generate test input
171 mt_srand( ++$this->fuzzSeed );
172 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
174 while ( strlen( $input ) < $totalLength ) {
175 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
176 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
177 $offset = mt_rand( 0, $dictSize - $hairLength );
178 $input .= substr( $dict, $offset, $hairLength );
181 $this->setupGlobals();
182 $parser = $this->getParser();
185 $parser->parse( $input, $title, $opts );
187 } catch ( Exception $exception ) {
192 echo "Test failed with seed {$this->fuzzSeed}\n";
201 $this->teardownGlobals();
202 $parser->__destruct();
204 if ( $numTotal % 100 == 0 ) {
205 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
206 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
208 echo "Out of memory:\n";
209 $memStats = $this->getMemoryBreakdown();
210 foreach ( $memStats as $name => $usage ) {
211 echo "$name: $usage\n";
220 * Get an input dictionary from a set of parser test files
222 function getFuzzInput( $filenames ) {
224 foreach( $filenames as $filename ) {
225 $contents = file_get_contents( $filename );
226 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
227 foreach ( $matches[1] as $match ) {
228 $dict .= $match . "\n";
235 * Get a memory usage breakdown
237 function getMemoryBreakdown() {
239 foreach ( $GLOBALS as $name => $value ) {
240 $memStats['$'.$name] = strlen( serialize( $value ) );
242 $classes = get_declared_classes();
243 foreach ( $classes as $class ) {
244 $rc = new ReflectionClass( $class );
245 $props = $rc->getStaticProperties();
246 $memStats[$class] = strlen( serialize( $props ) );
247 $methods = $rc->getMethods();
248 foreach ( $methods as $method ) {
249 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
252 $functions = get_defined_functions();
253 foreach ( $functions['user'] as $function ) {
254 $rf = new ReflectionFunction( $function );
255 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
266 * Run a series of tests listed in the given text files.
267 * Each test consists of a brief description, wikitext input,
268 * and the expected HTML output.
270 * Prints status updates on stdout and counts up the total
271 * number and percentage of passed tests.
273 * @param array of strings $filenames
274 * @return bool True if passed all tests, false if any tests failed.
276 public function runTestsFromFiles( $filenames ) {
277 $this->recorder->start();
278 $this->setupDatabase();
280 foreach( $filenames as $filename ) {
281 $tests = new TestFileIterator( $filename, $this );
282 $ok = $this->runTests( $tests ) && $ok;
284 $this->teardownDatabase();
285 $this->recorder->report();
286 $this->recorder->end();
290 function runTests($tests) {
292 foreach($tests as $i => $t) {
294 $this->runTest($t['test'], $t['input'], $t['result'], $t['options'], $t['config']);
295 $ok = $ok && $result;
296 $this->recorder->record( $t['test'], $result );
298 if ( $this->showProgress ) {
304 * Get a Parser object
306 function getParser() {
307 global $wgParserConf;
308 $class = $wgParserConf['class'];
309 $parser = new $class( $wgParserConf );
310 foreach( $this->hooks as $tag => $callback ) {
311 $parser->setHook( $tag, $callback );
313 foreach( $this->functionHooks as $tag => $bits ) {
314 list( $callback, $flags ) = $bits;
315 $parser->setFunctionHook( $tag, $callback, $flags );
317 wfRunHooks( 'ParserTestParser', array( &$parser ) );
322 * Run a given wikitext input through a freshly-constructed wiki parser,
323 * and compare the output against the expected results.
324 * Prints status and explanatory messages to stdout.
326 * @param string $input Wikitext to try rendering
327 * @param string $result Result to output
330 public function runTest( $desc, $input, $result, $opts, $config ) {
331 if( $this->showProgress ) {
332 $this->showTesting( $desc );
335 $opts = $this->parseOptions( $opts );
336 $this->setupGlobals($opts, $config);
339 $options = ParserOptions::newFromUser( $user );
342 if (isset( $opts['title'] ) ) {
343 $titleText = $opts['title'];
346 $titleText = 'Parser test';
349 $noxml = isset( $opts['noxml'] );
350 $local = isset( $opts['local'] );
351 $parser = $this->getParser();
352 $title = Title::newFromText( $titleText );
355 if( isset( $opts['pst'] ) ) {
356 $out = $parser->preSaveTransform( $input, $title, $user, $options );
357 } elseif( isset( $opts['msg'] ) ) {
358 $out = $parser->transformMsg( $input, $options );
359 } elseif( isset( $opts['section'] ) ) {
360 $section = $opts['section'];
361 $out = $parser->getSection( $input, $section );
362 } elseif( isset( $opts['replace'] ) ) {
363 $section = $opts['replace'][0];
364 $replace = $opts['replace'][1];
365 $out = $parser->replaceSection( $input, $section, $replace );
366 } elseif( isset( $opts['comment'] ) ) {
367 $linker = $user->getSkin();
368 $out = $linker->formatComment( $input, $title, $local );
370 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
371 $out = $output->getText();
373 if ( isset( $opts['showtitle'] ) ) {
374 $out = $output->getTitleText() . "\n$out";
376 if (isset( $opts['ill'] ) ) {
377 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
378 } elseif( isset( $opts['cat'] ) ) {
380 $wgOut->addCategoryLinks($output->getCategories());
381 $cats = $wgOut->getCategoryLinks();
382 if ( isset( $cats['normal'] ) ) {
383 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
389 $result = $this->tidy($result);
393 $this->teardownGlobals();
395 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
396 return $this->showSuccess( $desc );
398 return $this->showFailure( $desc, $result, $out );
404 * Use a regex to find out the value of an option
405 * @param $key name of option val to retrieve
406 * @param $opts Options array to look in
407 * @param $defaults Default value returned if not found
409 private static function getOptionValue( $key, $opts, $default ) {
410 $key = strtolower( $key );
411 if( isset( $opts[$key] ) ) {
418 private function parseOptions( $instring ) {
420 $lines = explode( "\n", $instring );
425 // foo=bar,"baz quux"
449 \[\[[^]]*\]\] # Link target
457 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
458 foreach( $matches as $bits ) {
459 $match = array_shift( $bits );
460 $key = strtolower( array_shift( $bits ) );
461 if( count( $bits ) == 0 ) {
463 } elseif( count( $bits ) == 1 ) {
464 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
467 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
474 private function cleanupOption( $opt ) {
475 if( substr( $opt, 0, 1 ) == '"' ) {
476 return substr( $opt, 1, -1 );
478 if( substr( $opt, 0, 2 ) == '[[' ) {
479 return substr( $opt, 2, -2 );
485 * Set up the global variables for a consistent environment for each test.
486 * Ideally this should replace the global configuration entirely.
488 private function setupGlobals($opts = '', $config = '') {
490 if( !isset( $this->uploadDir ) ) {
491 $this->uploadDir = $this->setupUploadDir();
494 # Find out values for some special options.
496 self::getOptionValue( 'language', $opts, 'en' );
498 self::getOptionValue( 'variant', $opts, false );
500 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
501 $linkHolderBatchSize =
502 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
505 'wgServer' => 'http://localhost',
506 'wgScript' => '/index.php',
507 'wgScriptPath' => '/',
508 'wgArticlePath' => '/wiki/$1',
509 'wgActionPaths' => array(),
510 'wgLocalFileRepo' => array(
511 'class' => 'LocalRepo',
513 'directory' => $this->uploadDir,
514 'url' => 'http://example.com/images',
516 'transformVia404' => false,
518 'wgEnableUploads' => true,
519 'wgStyleSheetPath' => '/skins',
520 'wgSitename' => 'MediaWiki',
521 'wgServerName' => 'Britney-Spears',
522 'wgLanguageCode' => $lang,
523 'wgContLanguageCode' => $lang,
524 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
525 'wgRawHtml' => isset( $opts['rawhtml'] ),
527 'wgContLang' => null,
528 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
529 'wgMaxTocLevel' => $maxtoclevel,
530 'wgCapitalLinks' => true,
531 'wgNoFollowLinks' => true,
532 'wgNoFollowDomainExceptions' => array(),
533 'wgThumbnailScriptPath' => false,
534 'wgUseImageResize' => false,
535 'wgUseTeX' => isset( $opts['math'] ),
536 'wgMathDirectory' => $this->uploadDir . '/math',
537 'wgLocaltimezone' => 'UTC',
538 'wgAllowExternalImages' => true,
539 'wgUseTidy' => false,
540 'wgDefaultLanguageVariant' => $variant,
541 'wgVariantArticlePath' => false,
542 'wgGroupPermissions' => array( '*' => array(
543 'createaccount' => true,
546 'createpage' => true,
547 'createtalk' => true,
549 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
550 'wgDefaultExternalStore' => array(),
551 'wgForeignFileRepos' => array(),
552 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
553 'wgExperimentalHtmlIds' => false,
554 'wgExternalLinkTarget' => false,
555 'wgAlwaysUseTidy' => false,
557 'wgWellFormedXml' => true,
558 'wgAllowMicrodataAttributes' => true,
562 $configLines = explode( "\n", $config );
564 foreach( $configLines as $line ) {
565 list( $var, $value ) = explode( '=', $line, 2 );
567 $settings[$var] = eval("return $value;" );
571 $this->savedGlobals = array();
572 foreach( $settings as $var => $val ) {
573 if( array_key_exists( $var, $GLOBALS ) ) {
574 $this->savedGlobals[$var] = $GLOBALS[$var];
576 $GLOBALS[$var] = $val;
578 $langObj = Language::factory( $lang );
579 $GLOBALS['wgLang'] = $langObj;
580 $GLOBALS['wgContLang'] = $langObj;
581 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
582 $GLOBALS['wgOut'] = new OutputPage;
584 MagicWord::clearCache();
587 $wgUser = new User();
591 * List of temporary tables to create, without prefix.
592 * Some of these probably aren't necessary.
594 private function listTables() {
596 $tables = array('user', 'page', 'page_restrictions',
597 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
598 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
599 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
600 'recentchanges', 'watchlist', 'math', 'interwiki',
601 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
602 'archive', 'user_groups', 'page_props', 'category'
605 if ($wgDBtype === 'mysql')
606 array_push( $tables, 'searchindex' );
608 // Allow extensions to add to the list of tables to duplicate;
609 // may be necessary if they hook into page save or other code
610 // which will require them while running tests.
611 wfRunHooks( 'ParserTestTables', array( &$tables ) );
617 * Set up a temporary set of wiki tables to work with for the tests.
618 * Currently this will only be done once per run, and any changes to
619 * the db will be visible to later tests in the run.
621 function setupDatabase() {
622 global $wgDBprefix, $wgDBtype;
623 if ( $this->databaseSetupDone ) {
626 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
627 throw new MWException( 'setupDatabase should be called before setupGlobals' );
629 $this->databaseSetupDone = true;
630 $this->oldTablePrefix = $wgDBprefix;
632 # CREATE TEMPORARY TABLE breaks if there is more than one server
633 # FIXME: r40209 makes temporary tables break even with just one server
634 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
635 if ( true || wfGetLB()->getServerCount() != 1 ) {
636 $this->useTemporaryTables = false;
639 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
641 $db = wfGetDB( DB_MASTER );
642 $tables = $this->listTables();
644 foreach ( $tables as $tbl ) {
645 # Clean up from previous aborted run. So that table escaping
646 # works correctly across DB engines, we need to change the pre-
647 # fix back and forth so tableName() works right.
648 $this->changePrefix( $this->oldTablePrefix );
649 $oldTableName = $db->tableName( $tbl );
650 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
651 $newTableName = $db->tableName( $tbl );
653 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
654 $db->query( "DROP TABLE $newTableName" );
657 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
659 if ($wgDBtype == 'oracle')
660 $db->query('BEGIN FILL_WIKI_INFO; END;');
662 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
664 # Hack: insert a few Wikipedia in-project interwiki prefixes,
665 # for testing inter-language links
666 $db->insert( 'interwiki', array(
667 array( 'iw_prefix' => 'wikipedia',
668 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
670 array( 'iw_prefix' => 'meatball',
671 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
673 array( 'iw_prefix' => 'zh',
674 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
676 array( 'iw_prefix' => 'es',
677 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
679 array( 'iw_prefix' => 'fr',
680 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
682 array( 'iw_prefix' => 'ru',
683 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
688 if ($wgDBtype == 'oracle') {
689 # Insert 0 and 1 user_ids to prevent FK violations
692 $db->insert( 'user', array(
694 'user_name' => 'Anonymous') );
696 # Hack-on-Hack: Insert a test user to be able to insert an image
697 $db->insert( 'user', array(
699 'user_name' => 'Tester') );
702 # Hack: Insert an image to work with
703 $db->insert( 'image', array(
704 'img_name' => 'Foobar.jpg',
706 'img_description' => 'Some lame file',
708 'img_user_text' => 'WikiSysop',
709 'img_timestamp' => $db->timestamp( '20010115123500' ),
713 'img_media_type' => MEDIATYPE_BITMAP,
714 'img_major_mime' => "image",
715 'img_minor_mime' => "jpeg",
716 'img_metadata' => serialize( array() ),
719 # This image will be blacklisted in [[MediaWiki:Bad image list]]
720 $db->insert( 'image', array(
721 'img_name' => 'Bad.jpg',
723 'img_description' => 'zomgnotcensored',
725 'img_user_text' => 'WikiSysop',
726 'img_timestamp' => $db->timestamp( '20010115123500' ),
730 'img_media_type' => MEDIATYPE_BITMAP,
731 'img_major_mime' => "image",
732 'img_minor_mime' => "jpeg",
733 'img_metadata' => serialize( array() ),
736 # Update certain things in site_stats
737 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
739 # Reinitialise the LocalisationCache to match the database state
740 Language::getLocalisationCache()->unloadAll();
742 # Make a new message cache
743 global $wgMessageCache, $wgMemc;
744 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
748 * Change the table prefix on all open DB connections/
750 protected function changePrefix( $prefix ) {
752 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
753 $wgDBprefix = $prefix;
756 public function changeLBPrefix( $lb, $prefix ) {
757 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
760 public function changeDBPrefix( $db, $prefix ) {
761 $db->tablePrefix( $prefix );
764 private function teardownDatabase() {
765 global $wgDBprefix, $wgDBtype;
766 if ( !$this->databaseSetupDone ) {
769 $this->changePrefix( $this->oldTablePrefix );
770 $this->databaseSetupDone = false;
771 if ( $this->useTemporaryTables ) {
772 # Don't need to do anything
777 $tables = $this->listTables();
778 $db = wfGetDB( DB_MASTER );
779 foreach ( $tables as $table ) {
780 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
783 if ($wgDBtype == 'oracle')
784 $db->query('BEGIN FILL_WIKI_INFO; END;');
789 * Create a dummy uploads directory which will contain a couple
790 * of files in order to pass existence tests.
791 * @return string The directory
793 private function setupUploadDir() {
795 if ( $this->keepUploads ) {
796 $dir = wfTempDir() . '/mwParser-images';
797 if ( is_dir( $dir ) ) {
801 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
804 wfDebug( "Creating upload directory $dir\n" );
805 if ( file_exists( $dir ) ) {
806 wfDebug( "Already exists!\n" );
809 wfMkdirParents( $dir . '/3/3a' );
810 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
812 wfMkdirParents( $dir . '/0/09' );
813 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
818 * Restore default values and perform any necessary clean-up
819 * after each test runs.
821 private function teardownGlobals() {
822 RepoGroup::destroySingleton();
823 LinkCache::singleton()->clear();
824 foreach( $this->savedGlobals as $var => $val ) {
825 $GLOBALS[$var] = $val;
827 if( isset( $this->uploadDir ) ) {
828 $this->teardownUploadDir( $this->uploadDir );
829 unset( $this->uploadDir );
834 * Remove the dummy uploads directory
836 private function teardownUploadDir( $dir ) {
837 if ( $this->keepUploads ) {
841 // delete the files first, then the dirs.
844 "$dir/3/3a/Foobar.jpg",
845 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
846 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
847 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
848 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
852 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
862 "$dir/thumb/3/3a/Foobar.jpg",
879 * Delete the specified files, if they exist.
880 * @param array $files full paths to files to delete.
882 private static function deleteFiles( $files ) {
883 foreach( $files as $file ) {
884 if( file_exists( $file ) ) {
891 * Delete the specified directories, if they exist. Must be empty.
892 * @param array $dirs full paths to directories to delete.
894 private static function deleteDirs( $dirs ) {
895 foreach( $dirs as $dir ) {
896 if( is_dir( $dir ) ) {
903 * "Running test $desc..."
905 protected function showTesting( $desc ) {
906 print "Running test $desc... ";
910 * Print a happy success message.
912 * @param string $desc The test name
915 protected function showSuccess( $desc ) {
916 if( $this->showProgress ) {
917 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
923 * Print a failure message and provide some explanatory output
924 * about what went wrong if so configured.
926 * @param string $desc The test name
927 * @param string $result Expected HTML output
928 * @param string $html Actual HTML output
931 protected function showFailure( $desc, $result, $html ) {
932 if( $this->showFailure ) {
933 if( !$this->showProgress ) {
934 # In quiet mode we didn't show the 'Testing' message before the
935 # test, in case it succeeded. Show it now:
936 $this->showTesting( $desc );
938 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
939 if ( $this->showOutput ) {
940 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
942 if( $this->showDiffs ) {
943 print $this->quickDiff( $result, $html );
944 if( !$this->wellFormed( $html ) ) {
945 print "XML error: $this->mXmlError\n";
953 * Run given strings through a diff and return the (colorized) output.
954 * Requires writable /tmp directory and a 'diff' command in the PATH.
956 * @param string $input
957 * @param string $output
958 * @param string $inFileTail Tailing for the input file name
959 * @param string $outFileTail Tailing for the output file name
962 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
963 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
965 $infile = "$prefix-$inFileTail";
966 $this->dumpToFile( $input, $infile );
968 $outfile = "$prefix-$outFileTail";
969 $this->dumpToFile( $output, $outfile );
971 $diff = `diff -au $infile $outfile`;
975 return $this->colorDiff( $diff );
979 * Write the given string to a file, adding a final newline.
981 * @param string $data
982 * @param string $filename
984 private function dumpToFile( $data, $filename ) {
985 $file = fopen( $filename, "wt" );
986 fwrite( $file, $data . "\n" );
991 * Colorize unified diff output if set for ANSI color output.
992 * Subtractions are colored blue, additions red.
994 * @param string $text
997 protected function colorDiff( $text ) {
999 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1000 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1001 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1006 * Show "Reading tests from ..."
1008 * @param String $path
1010 public function showRunFile( $path ){
1011 print $this->term->color( 1 ) .
1012 "Reading tests from \"$path\"..." .
1013 $this->term->reset() .
1018 * Insert a temporary test article
1019 * @param string $name the title, including any prefix
1020 * @param string $text the article text
1021 * @param int $line the input line number, for reporting errors
1023 public function addArticle($name, $text, $line) {
1024 $this->setupGlobals();
1025 $title = Title::newFromText( $name );
1026 if ( is_null($title) ) {
1027 wfDie( "invalid title at line $line\n" );
1030 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1032 wfDie( "duplicate article at line $line\n" );
1035 $art = new Article($title);
1036 $art->insertNewArticle($text, '', false, false );
1038 $this->teardownGlobals();
1042 * Steal a callback function from the primary parser, save it for
1043 * application to our scary parser. If the hook is not installed,
1044 * die a painful dead to warn the others.
1045 * @param string $name
1047 public function requireHook( $name ) {
1049 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1050 if( isset( $wgParser->mTagHooks[$name] ) ) {
1051 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1053 wfDie( "This test suite requires the '$name' hook extension.\n" );
1058 * Steal a callback function from the primary parser, save it for
1059 * application to our scary parser. If the hook is not installed,
1060 * die a painful dead to warn the others.
1061 * @param string $name
1063 private function requireFunctionHook( $name ) {
1065 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1066 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1067 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1069 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1074 * Run the "tidy" command on text if the $wgUseTidy
1077 * @param string $text the text to tidy
1081 private function tidy( $text ) {
1084 $text = Parser::tidy($text);
1089 private function wellFormed( $text ) {
1091 Sanitizer::hackDocType() .
1096 $parser = xml_parser_create( "UTF-8" );
1098 # case folding violates XML standard, turn it off
1099 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1101 if( !xml_parse( $parser, $html, true ) ) {
1102 $err = xml_error_string( xml_get_error_code( $parser ) );
1103 $position = xml_get_current_byte_index( $parser );
1104 $fragment = $this->extractFragment( $html, $position );
1105 $this->mXmlError = "$err at byte $position:\n$fragment";
1106 xml_parser_free( $parser );
1109 xml_parser_free( $parser );
1113 private function extractFragment( $text, $position ) {
1114 $start = max( 0, $position - 10 );
1115 $before = $position - $start;
1117 $this->term->color( 34 ) .
1118 substr( $text, $start, $before ) .
1119 $this->term->color( 0 ) .
1120 $this->term->color( 31 ) .
1121 $this->term->color( 1 ) .
1122 substr( $text, $position, 1 ) .
1123 $this->term->color( 0 ) .
1124 $this->term->color( 34 ) .
1125 substr( $text, $position + 1, 9 ) .
1126 $this->term->color( 0 ) .
1128 $display = str_replace( "\n", ' ', $fragment );
1130 str_repeat( ' ', $before ) .
1131 $this->term->color( 31 ) .
1133 $this->term->color( 0 );
1134 return "$display\n$caret";
1138 class AnsiTermColorer {
1139 function __construct() {
1143 * Return ANSI terminal escape code for changing text attribs/color
1145 * @param string $color Semicolon-separated list of attribute/color codes
1148 public function color( $color ) {
1149 global $wgCommandLineDarkBg;
1150 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1151 return "\x1b[{$light}{$color}m";
1155 * Return ANSI terminal escape code for restoring default text attributes
1159 public function reset() {
1160 return $this->color( 0 );
1164 /* A colour-less terminal */
1165 class DummyTermColorer {
1166 public function color( $color ) {
1170 public function reset() {
1175 class TestRecorder {
1179 function __construct( $parent ) {
1180 $this->parent = $parent;
1181 $this->term = $parent->term;
1189 function record( $test, $result ) {
1191 $this->success += ($result ? 1 : 0);
1199 if( $this->total > 0 ) {
1200 $this->reportPercentage( $this->success, $this->total );
1202 wfDie( "No tests found.\n" );
1206 function reportPercentage( $success, $total ) {
1207 $ratio = wfPercent( 100 * $success / $total );
1208 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1209 if( $success == $total ) {
1210 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1212 $failed = $total - $success ;
1213 print $this->term->color( 31 ) . "$failed tests failed!";
1215 print $this->term->reset() . "\n";
1216 return ($success == $total);
1220 class DbTestPreviewer extends TestRecorder {
1221 protected $lb; ///< Database load balancer
1222 protected $db; ///< Database connection to the main DB
1223 protected $curRun; ///< run ID number for the current run
1224 protected $prevRun; ///< run ID number for the previous run, if any
1225 protected $results; ///< Result array
1228 * This should be called before the table prefix is changed
1230 function __construct( $parent ) {
1231 parent::__construct( $parent );
1232 $this->lb = wfGetLBFactory()->newMainLB();
1233 // This connection will have the wiki's table prefix, not parsertest_
1234 $this->db = $this->lb->getConnection( DB_MASTER );
1238 * Set up result recording; insert a record for the run with the date
1239 * and all that fun stuff
1242 global $wgDBtype, $wgDBprefix;
1245 if( ! $this->db->tableExists( 'testrun' )
1246 or ! $this->db->tableExists( 'testitem' ) )
1248 print "WARNING> `testrun` table not found in database.\n";
1249 $this->prevRun = false;
1251 // We'll make comparisons against the previous run later...
1252 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1254 $this->results = array();
1257 function record( $test, $result ) {
1258 parent::record( $test, $result );
1259 $this->results[$test] = $result;
1263 if( $this->prevRun ) {
1264 // f = fail, p = pass, n = nonexistent
1265 // codes show before then after
1267 'fp' => 'previously failing test(s) now PASSING! :)',
1268 'pn' => 'previously PASSING test(s) removed o_O',
1269 'np' => 'new PASSING test(s) :)',
1271 'pf' => 'previously passing test(s) now FAILING! :(',
1272 'fn' => 'previously FAILING test(s) removed O_o',
1273 'nf' => 'new FAILING test(s) :(',
1274 'ff' => 'still FAILING test(s) :(',
1277 $prevResults = array();
1279 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1280 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1281 foreach ( $res as $row ) {
1282 if ( !$this->parent->regex
1283 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1285 $prevResults[$row->ti_name] = $row->ti_success;
1289 $combined = array_keys( $this->results + $prevResults );
1291 # Determine breakdown by change type
1292 $breakdown = array();
1293 foreach ( $combined as $test ) {
1294 if ( !isset( $prevResults[$test] ) ) {
1296 } elseif ( $prevResults[$test] == 1 ) {
1298 } else /* if ( $prevResults[$test] == 0 )*/ {
1301 if ( !isset( $this->results[$test] ) ) {
1303 } elseif ( $this->results[$test] == 1 ) {
1305 } else /*if ( $this->results[$test] == 0 ) */ {
1308 $code = $before . $after;
1309 if ( isset( $table[$code] ) ) {
1310 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1315 foreach ( $table as $code => $label ) {
1316 if( !empty( $breakdown[$code] ) ) {
1317 $count = count($breakdown[$code]);
1318 printf( "\n%4d %s\n", $count, $label );
1319 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1320 print " * $differing_test_name [$statusInfo]\n";
1325 print "No previous test runs to compare against.\n";
1332 ** Returns a string giving information about when a test last had a status change.
1333 ** Could help to track down when regressions were introduced, as distinct from tests
1334 ** which have never passed (which are more change requests than regressions).
1336 private function getTestStatusInfo($testname, $after) {
1338 // If we're looking at a test that has just been removed, then say when it first appeared.
1339 if ( $after == 'n' ) {
1340 $changedRun = $this->db->selectField ( 'testitem',
1342 array( 'ti_name' => $testname ),
1344 $appear = $this->db->selectRow ( 'testrun',
1345 array( 'tr_date', 'tr_mw_version' ),
1346 array( 'tr_id' => $changedRun ),
1348 return "First recorded appearance: "
1349 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1350 . ", " . $appear->tr_mw_version;
1353 // Otherwise, this test has previous recorded results.
1354 // See when this test last had a different result to what we're seeing now.
1356 'ti_name' => $testname,
1357 'ti_success' => ($after == 'f' ? "1" : "0") );
1358 if ( $this->curRun ) {
1359 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1362 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1364 // If no record of ever having had a different result.
1365 if ( is_null ( $changedRun ) ) {
1366 if ($after == "f") {
1367 return "Has never passed";
1369 return "Has never failed";
1373 // Otherwise, we're looking at a test whose status has changed.
1374 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1375 // In this situation, give as much info as we can as to when it changed status.
1376 $pre = $this->db->selectRow ( 'testrun',
1377 array( 'tr_date', 'tr_mw_version' ),
1378 array( 'tr_id' => $changedRun ),
1380 $post = $this->db->selectRow ( 'testrun',
1381 array( 'tr_date', 'tr_mw_version' ),
1382 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1384 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1388 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1392 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1393 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1399 * Commit transaction and clean up for result recording
1402 $this->lb->commitMasterChanges();
1403 $this->lb->closeAll();
1409 class DbTestRecorder extends DbTestPreviewer {
1411 * Set up result recording; insert a record for the run with the date
1412 * and all that fun stuff
1415 global $wgDBtype, $wgDBprefix, $options;
1418 if( ! $this->db->tableExists( 'testrun' )
1419 or ! $this->db->tableExists( 'testitem' ) )
1421 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1422 if ($wgDBtype === 'postgres')
1423 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1424 elseif ($wgDBtype === 'oracle')
1425 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1427 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1428 echo "OK, resuming.\n";
1433 $this->db->insert( 'testrun',
1435 'tr_date' => $this->db->timestamp(),
1436 'tr_mw_version' => isset( $options['setversion'] ) ?
1437 $options['setversion'] : SpecialVersion::getVersion(),
1438 'tr_php_version' => phpversion(),
1439 'tr_db_version' => $this->db->getServerVersion(),
1440 'tr_uname' => php_uname()
1443 if ($wgDBtype === 'postgres')
1444 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1446 $this->curRun = $this->db->insertId();
1450 * Record an individual test item's success or failure to the db
1451 * @param string $test
1452 * @param bool $result
1454 function record( $test, $result ) {
1455 parent::record( $test, $result );
1456 $this->db->insert( 'testitem',
1458 'ti_run' => $this->curRun,
1460 'ti_success' => $result ? 1 : 0,
1466 class RemoteTestRecorder extends TestRecorder {
1469 $this->results = array();
1470 $this->ping( 'running' );
1473 function record( $test, $result ) {
1474 parent::record( $test, $result );
1475 $this->results[$test] = (bool)$result;
1479 $this->ping( 'complete', $this->results );
1484 * Inform a CodeReview instance that we've started or completed a test run...
1485 * @param $remote array: info on remote target
1486 * @param $status string: "running" - tell it we've started
1487 * "complete" - provide test results array
1488 * "abort" - something went horribly awry
1489 * @param $data array of test name => true/false
1491 function ping( $status, $results=false ) {
1492 global $wgParserTestRemote, $IP;
1494 $remote = $wgParserTestRemote;
1495 $revId = SpecialVersion::getSvnRevision( $IP );
1496 $jsonResults = json_encode( $results );
1499 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1503 // Generate a hash MAC to validate our credentials
1510 if( $status == "complete" ) {
1511 $message[] = $jsonResults;
1513 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1516 'action' => 'codetestupload',
1518 'repo' => $remote['repo'],
1519 'suite' => $remote['suite'],
1521 'status' => $status,
1524 if( $status == "complete" ) {
1525 $postData['results'] = $jsonResults;
1527 $response = $this->post( $remote['api-url'], $postData );
1529 if( $response === false ) {
1530 print "CodeReview info upload failed to reach server.\n";
1533 $responseData = json_decode( $response, true );
1534 if( !is_array( $responseData ) ) {
1535 print "CodeReview API response not recognized...\n";
1536 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1539 if( isset( $responseData['error'] ) ) {
1540 $code = $responseData['error']['code'];
1541 $info = $responseData['error']['info'];
1542 print "CodeReview info upload failed: $code $info\n";
1547 function post( $url, $data ) {
1548 return Http::post( $url, array( 'postData' => $data) );
1552 class TestFileIterator implements Iterator {
1561 function __construct( $file, $parser = null ) {
1564 $this->file = $file;
1565 $this->fh = fopen($this->file, "r");
1567 wfDie( "Couldn't open file '$file'\n" );
1570 $this->parser = $parser;
1572 if( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1573 $this->lineNum = $this->index = 0;
1576 function setParser( ParserTest $parser ) {
1577 $this->parser = $parser;
1581 if(fseek($this->fh, 0)) {
1582 wfDie( "Couldn't fseek to the start of '$filename'\n" );
1587 $this->readNextTest();
1592 function current() {
1597 return $this->index;
1601 if($this->readNextTest()) {
1610 return $this->eof != true;
1613 function readNextTest() {
1617 while( false !== ($line = fgets( $this->fh ) ) ) {
1620 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1621 $section = strtolower( $matches[1] );
1622 if( $section == 'endarticle') {
1623 if( !isset( $data['text'] ) ) {
1624 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
1626 if( !isset( $data['article'] ) ) {
1627 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
1629 if( $this->parser ) $this->parser->addArticle($this->parser->chomp($data['article']), $this->parser->chomp($data['text']),
1635 if( $section == 'endhooks' ) {
1636 if( !isset( $data['hooks'] ) ) {
1637 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
1639 foreach( explode( "\n", $data['hooks'] ) as $line ) {
1640 $line = trim( $line );
1642 if( $this->parser ) $this->parser->requireHook( $line );
1649 if( $section == 'endfunctionhooks' ) {
1650 if( !isset( $data['functionhooks'] ) ) {
1651 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
1653 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
1654 $line = trim( $line );
1656 if( $this->parser ) $this->parser->requireFunctionHook( $line );
1663 if( $section == 'end' ) {
1664 if( !isset( $data['test'] ) ) {
1665 wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
1667 if( !isset( $data['input'] ) ) {
1668 wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
1670 if( !isset( $data['result'] ) ) {
1671 wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
1673 if( !isset( $data['options'] ) ) {
1674 $data['options'] = '';
1676 if (!isset( $data['config'] ) )
1677 $data['config'] = '';
1679 if ( $this->parser && (preg_match('/\\bdisabled\\b/i', $data['options'])
1680 || !preg_match("/{$this->parser->regex}/i", $data['test'])) && !$this->parser->runDisabled ) {
1686 if ( $this->parser &&
1687 preg_match('/\\bmath\\b/i', $data['options']) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1688 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1694 if( $this->parser ) {
1695 $this->test = array(
1696 'test' => $this->parser->chomp( $data['test'] ),
1697 'input' => $this->parser->chomp( $data['input'] ),
1698 'result' => $this->parser->chomp( $data['result'] ),
1699 'options' => $this->parser->chomp( $data['options'] ),
1700 'config' => $this->parser->chomp( $data['config'] ) );
1702 $this->test['test'] = $data['test'];
1706 if ( isset ($data[$section] ) ) {
1707 wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
1709 $data[$section] = '';
1713 $data[$section] .= $line;