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 $filenames Array of strings
274 * @return Boolean: 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 ) {
305 * Get a Parser object
307 function getParser($preprocessor = null) {
308 global $wgParserConf;
309 $class = $wgParserConf['class'];
310 $parser = new $class( array( 'preprocessorClass'=>$preprocessor ) + $wgParserConf );
311 foreach( $this->hooks as $tag => $callback ) {
312 $parser->setHook( $tag, $callback );
314 foreach( $this->functionHooks as $tag => $bits ) {
315 list( $callback, $flags ) = $bits;
316 $parser->setFunctionHook( $tag, $callback, $flags );
318 wfRunHooks( 'ParserTestParser', array( &$parser ) );
323 * Run a given wikitext input through a freshly-constructed wiki parser,
324 * and compare the output against the expected results.
325 * Prints status and explanatory messages to stdout.
327 * @param $desc String: test's description
328 * @param $input String: wikitext to try rendering
329 * @param $result String: result to output
330 * @param $opts Array: test's options
331 * @param $config String: overrides for global variables, one per line
334 public function runTest( $desc, $input, $result, $opts, $config ) {
335 if( $this->showProgress ) {
336 $this->showTesting( $desc );
339 $opts = $this->parseOptions( $opts );
340 $this->setupGlobals($opts, $config);
343 $options = ParserOptions::newFromUser( $user );
346 if (isset( $opts['title'] ) ) {
347 $titleText = $opts['title'];
350 $titleText = 'Parser test';
353 $noxml = isset( $opts['noxml'] );
354 $local = isset( $opts['local'] );
355 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
356 $parser = $this->getParser( $preprocessor );
357 $title = Title::newFromText( $titleText );
360 if( isset( $opts['pst'] ) ) {
361 $out = $parser->preSaveTransform( $input, $title, $user, $options );
362 } elseif( isset( $opts['msg'] ) ) {
363 $out = $parser->transformMsg( $input, $options );
364 } elseif( isset( $opts['section'] ) ) {
365 $section = $opts['section'];
366 $out = $parser->getSection( $input, $section );
367 } elseif( isset( $opts['replace'] ) ) {
368 $section = $opts['replace'][0];
369 $replace = $opts['replace'][1];
370 $out = $parser->replaceSection( $input, $section, $replace );
371 } elseif( isset( $opts['comment'] ) ) {
372 $linker = $user->getSkin();
373 $out = $linker->formatComment( $input, $title, $local );
374 } elseif( isset( $opts['preload'] ) ) {
375 $out = $parser->getpreloadText( $input, $title, $options );
377 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
378 $out = $output->getText();
380 if ( isset( $opts['showtitle'] ) ) {
381 if($output->getTitleText()) $title = $output->getTitleText();
382 $out = "$title\n$out";
384 if (isset( $opts['ill'] ) ) {
385 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
386 } elseif( isset( $opts['cat'] ) ) {
388 $wgOut->addCategoryLinks($output->getCategories());
389 $cats = $wgOut->getCategoryLinks();
390 if ( isset( $cats['normal'] ) ) {
391 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
397 $result = $this->tidy($result);
401 $this->teardownGlobals();
403 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
404 return $this->showSuccess( $desc );
406 return $this->showFailure( $desc, $result, $out );
412 * Use a regex to find out the value of an option
413 * @param $key String: name of option val to retrieve
414 * @param $opts Options array to look in
415 * @param $default Mixed: default value returned if not found
417 private static function getOptionValue( $key, $opts, $default ) {
418 $key = strtolower( $key );
419 if( isset( $opts[$key] ) ) {
426 private function parseOptions( $instring ) {
428 $lines = explode( "\n", $instring );
433 // foo=bar,"baz quux"
457 \[\[[^]]*\]\] # Link target
465 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
466 foreach( $matches as $bits ) {
467 $match = array_shift( $bits );
468 $key = strtolower( array_shift( $bits ) );
469 if( count( $bits ) == 0 ) {
471 } elseif( count( $bits ) == 1 ) {
472 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
475 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
482 private function cleanupOption( $opt ) {
483 if( substr( $opt, 0, 1 ) == '"' ) {
484 return substr( $opt, 1, -1 );
486 if( substr( $opt, 0, 2 ) == '[[' ) {
487 return substr( $opt, 2, -2 );
493 * Set up the global variables for a consistent environment for each test.
494 * Ideally this should replace the global configuration entirely.
496 private function setupGlobals($opts = '', $config = '') {
498 if( !isset( $this->uploadDir ) ) {
499 $this->uploadDir = $this->setupUploadDir();
502 # Find out values for some special options.
504 self::getOptionValue( 'language', $opts, 'en' );
506 self::getOptionValue( 'variant', $opts, false );
508 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
509 $linkHolderBatchSize =
510 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
513 'wgServer' => 'http://localhost',
514 'wgScript' => '/index.php',
515 'wgScriptPath' => '/',
516 'wgArticlePath' => '/wiki/$1',
517 'wgActionPaths' => array(),
518 'wgLocalFileRepo' => array(
519 'class' => 'LocalRepo',
521 'directory' => $this->uploadDir,
522 'url' => 'http://example.com/images',
524 'transformVia404' => false,
526 'wgEnableUploads' => true,
527 'wgStyleSheetPath' => '/skins',
528 'wgSitename' => 'MediaWiki',
529 'wgServerName' => 'Britney-Spears',
530 'wgLanguageCode' => $lang,
531 'wgContLanguageCode' => $lang,
532 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
533 'wgRawHtml' => isset( $opts['rawhtml'] ),
535 'wgContLang' => null,
536 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
537 'wgMaxTocLevel' => $maxtoclevel,
538 'wgCapitalLinks' => true,
539 'wgNoFollowLinks' => true,
540 'wgNoFollowDomainExceptions' => array(),
541 'wgThumbnailScriptPath' => false,
542 'wgUseImageResize' => false,
543 'wgUseTeX' => isset( $opts['math'] ),
544 'wgMathDirectory' => $this->uploadDir . '/math',
545 'wgLocaltimezone' => 'UTC',
546 'wgAllowExternalImages' => true,
547 'wgUseTidy' => false,
548 'wgDefaultLanguageVariant' => $variant,
549 'wgVariantArticlePath' => false,
550 'wgGroupPermissions' => array( '*' => array(
551 'createaccount' => true,
554 'createpage' => true,
555 'createtalk' => true,
557 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
558 'wgDefaultExternalStore' => array(),
559 'wgForeignFileRepos' => array(),
560 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
561 'wgExperimentalHtmlIds' => false,
562 'wgExternalLinkTarget' => false,
563 'wgAlwaysUseTidy' => false,
565 'wgWellFormedXml' => true,
566 'wgAllowMicrodataAttributes' => true,
570 $configLines = explode( "\n", $config );
572 foreach( $configLines as $line ) {
573 list( $var, $value ) = explode( '=', $line, 2 );
575 $settings[$var] = eval("return $value;" );
579 $this->savedGlobals = array();
580 foreach( $settings as $var => $val ) {
581 if( array_key_exists( $var, $GLOBALS ) ) {
582 $this->savedGlobals[$var] = $GLOBALS[$var];
584 $GLOBALS[$var] = $val;
586 $langObj = Language::factory( $lang );
587 $GLOBALS['wgLang'] = $langObj;
588 $GLOBALS['wgContLang'] = $langObj;
589 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
590 $GLOBALS['wgOut'] = new OutputPage;
592 MagicWord::clearCache();
595 $wgUser = new User();
599 * List of temporary tables to create, without prefix.
600 * Some of these probably aren't necessary.
602 private function listTables() {
604 $tables = array('user', 'page', 'page_restrictions',
605 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
606 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
607 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
608 'recentchanges', 'watchlist', 'math', 'interwiki',
609 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
610 'archive', 'user_groups', 'page_props', 'category'
613 if ($wgDBtype === 'mysql')
614 array_push( $tables, 'searchindex' );
616 // Allow extensions to add to the list of tables to duplicate;
617 // may be necessary if they hook into page save or other code
618 // which will require them while running tests.
619 wfRunHooks( 'ParserTestTables', array( &$tables ) );
625 * Set up a temporary set of wiki tables to work with for the tests.
626 * Currently this will only be done once per run, and any changes to
627 * the db will be visible to later tests in the run.
629 function setupDatabase() {
630 global $wgDBprefix, $wgDBtype;
631 if ( $this->databaseSetupDone ) {
634 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
635 throw new MWException( 'setupDatabase should be called before setupGlobals' );
637 $this->databaseSetupDone = true;
638 $this->oldTablePrefix = $wgDBprefix;
640 # CREATE TEMPORARY TABLE breaks if there is more than one server
641 # FIXME: r40209 makes temporary tables break even with just one server
642 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
643 if ( true || wfGetLB()->getServerCount() != 1 ) {
644 $this->useTemporaryTables = false;
647 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
649 $db = wfGetDB( DB_MASTER );
650 $tables = $this->listTables();
652 foreach ( $tables as $tbl ) {
653 # Clean up from previous aborted run. So that table escaping
654 # works correctly across DB engines, we need to change the pre-
655 # fix back and forth so tableName() works right.
656 $this->changePrefix( $this->oldTablePrefix );
657 $oldTableName = $db->tableName( $tbl );
658 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
659 $newTableName = $db->tableName( $tbl );
661 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
662 $db->query( "DROP TABLE $newTableName" );
665 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
667 if ($wgDBtype == 'oracle')
668 $db->query('BEGIN FILL_WIKI_INFO; END;');
670 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
672 # Hack: insert a few Wikipedia in-project interwiki prefixes,
673 # for testing inter-language links
674 $db->insert( 'interwiki', array(
675 array( 'iw_prefix' => 'wikipedia',
676 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
678 array( 'iw_prefix' => 'meatball',
679 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
681 array( 'iw_prefix' => 'zh',
682 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
684 array( 'iw_prefix' => 'es',
685 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
687 array( 'iw_prefix' => 'fr',
688 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
690 array( 'iw_prefix' => 'ru',
691 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
696 if ($wgDBtype == 'oracle') {
697 # Insert 0 and 1 user_ids to prevent FK violations
700 $db->insert( 'user', array(
702 'user_name' => 'Anonymous') );
704 # Hack-on-Hack: Insert a test user to be able to insert an image
705 $db->insert( 'user', array(
707 'user_name' => 'Tester') );
710 # Hack: Insert an image to work with
711 $db->insert( 'image', array(
712 'img_name' => 'Foobar.jpg',
714 'img_description' => 'Some lame file',
716 'img_user_text' => 'WikiSysop',
717 'img_timestamp' => $db->timestamp( '20010115123500' ),
721 'img_media_type' => MEDIATYPE_BITMAP,
722 'img_major_mime' => "image",
723 'img_minor_mime' => "jpeg",
724 'img_metadata' => serialize( array() ),
727 # This image will be blacklisted in [[MediaWiki:Bad image list]]
728 $db->insert( 'image', array(
729 'img_name' => 'Bad.jpg',
731 'img_description' => 'zomgnotcensored',
733 'img_user_text' => 'WikiSysop',
734 'img_timestamp' => $db->timestamp( '20010115123500' ),
738 'img_media_type' => MEDIATYPE_BITMAP,
739 'img_major_mime' => "image",
740 'img_minor_mime' => "jpeg",
741 'img_metadata' => serialize( array() ),
744 # Update certain things in site_stats
745 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
747 # Reinitialise the LocalisationCache to match the database state
748 Language::getLocalisationCache()->unloadAll();
750 # Make a new message cache
751 global $wgMessageCache, $wgMemc;
752 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
756 * Change the table prefix on all open DB connections/
758 protected function changePrefix( $prefix ) {
760 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
761 $wgDBprefix = $prefix;
764 public function changeLBPrefix( $lb, $prefix ) {
765 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
768 public function changeDBPrefix( $db, $prefix ) {
769 $db->tablePrefix( $prefix );
772 private function teardownDatabase() {
774 if ( !$this->databaseSetupDone ) {
777 $this->changePrefix( $this->oldTablePrefix );
778 $this->databaseSetupDone = false;
779 if ( $this->useTemporaryTables ) {
780 # Don't need to do anything
785 $tables = $this->listTables();
786 $db = wfGetDB( DB_MASTER );
787 foreach ( $tables as $table ) {
788 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
791 if ($wgDBtype == 'oracle')
792 $db->query('BEGIN FILL_WIKI_INFO; END;');
797 * Create a dummy uploads directory which will contain a couple
798 * of files in order to pass existence tests.
800 * @return String: the directory
802 private function setupUploadDir() {
804 if ( $this->keepUploads ) {
805 $dir = wfTempDir() . '/mwParser-images';
806 if ( is_dir( $dir ) ) {
810 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
813 wfDebug( "Creating upload directory $dir\n" );
814 if ( file_exists( $dir ) ) {
815 wfDebug( "Already exists!\n" );
818 wfMkdirParents( $dir . '/3/3a' );
819 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
821 wfMkdirParents( $dir . '/0/09' );
822 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
827 * Restore default values and perform any necessary clean-up
828 * after each test runs.
830 private function teardownGlobals() {
831 RepoGroup::destroySingleton();
832 LinkCache::singleton()->clear();
833 foreach( $this->savedGlobals as $var => $val ) {
834 $GLOBALS[$var] = $val;
836 if( isset( $this->uploadDir ) ) {
837 $this->teardownUploadDir( $this->uploadDir );
838 unset( $this->uploadDir );
843 * Remove the dummy uploads directory
845 private function teardownUploadDir( $dir ) {
846 if ( $this->keepUploads ) {
850 // delete the files first, then the dirs.
853 "$dir/3/3a/Foobar.jpg",
854 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
855 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
856 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
857 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
861 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
871 "$dir/thumb/3/3a/Foobar.jpg",
888 * Delete the specified files, if they exist.
889 * @param $files Array: full paths to files to delete.
891 private static function deleteFiles( $files ) {
892 foreach( $files as $file ) {
893 if( file_exists( $file ) ) {
900 * Delete the specified directories, if they exist. Must be empty.
901 * @param $dirs Array: full paths to directories to delete.
903 private static function deleteDirs( $dirs ) {
904 foreach( $dirs as $dir ) {
905 if( is_dir( $dir ) ) {
912 * "Running test $desc..."
914 protected function showTesting( $desc ) {
915 print "Running test $desc... ";
919 * Print a happy success message.
921 * @param $desc String: the test name
924 protected function showSuccess( $desc ) {
925 if( $this->showProgress ) {
926 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
932 * Print a failure message and provide some explanatory output
933 * about what went wrong if so configured.
935 * @param $desc String: the test name
936 * @param $result String: expected HTML output
937 * @param $html String: actual HTML output
940 protected function showFailure( $desc, $result, $html ) {
941 if( $this->showFailure ) {
942 if( !$this->showProgress ) {
943 # In quiet mode we didn't show the 'Testing' message before the
944 # test, in case it succeeded. Show it now:
945 $this->showTesting( $desc );
947 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
948 if ( $this->showOutput ) {
949 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
951 if( $this->showDiffs ) {
952 print $this->quickDiff( $result, $html );
953 if( !$this->wellFormed( $html ) ) {
954 print "XML error: $this->mXmlError\n";
962 * Run given strings through a diff and return the (colorized) output.
963 * Requires writable /tmp directory and a 'diff' command in the PATH.
965 * @param $input String
966 * @param $output String
967 * @param $inFileTail String: tailing for the input file name
968 * @param $outFileTail String: tailing for the output file name
971 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
972 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
974 $infile = "$prefix-$inFileTail";
975 $this->dumpToFile( $input, $infile );
977 $outfile = "$prefix-$outFileTail";
978 $this->dumpToFile( $output, $outfile );
980 $diff = `diff -au $infile $outfile`;
984 return $this->colorDiff( $diff );
988 * Write the given string to a file, adding a final newline.
990 * @param $data String
991 * @param $filename String
993 private function dumpToFile( $data, $filename ) {
994 $file = fopen( $filename, "wt" );
995 fwrite( $file, $data . "\n" );
1000 * Colorize unified diff output if set for ANSI color output.
1001 * Subtractions are colored blue, additions red.
1003 * @param $text String
1006 protected function colorDiff( $text ) {
1007 return preg_replace(
1008 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1009 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1010 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1015 * Show "Reading tests from ..."
1017 * @param $path String
1019 public function showRunFile( $path ){
1020 print $this->term->color( 1 ) .
1021 "Reading tests from \"$path\"..." .
1022 $this->term->reset() .
1027 * Insert a temporary test article
1028 * @param $name String: the title, including any prefix
1029 * @param $text String: the article text
1030 * @param $line Integer: the input line number, for reporting errors
1032 public function addArticle($name, $text, $line) {
1033 $this->setupGlobals();
1034 $title = Title::newFromText( $name );
1035 if ( is_null($title) ) {
1036 wfDie( "invalid title at line $line\n" );
1039 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1041 wfDie( "duplicate article '$name' at line $line\n" );
1044 $art = new Article($title);
1045 $art->insertNewArticle($text, '', false, false );
1047 $this->teardownGlobals();
1051 * Steal a callback function from the primary parser, save it for
1052 * application to our scary parser. If the hook is not installed,
1053 * die a painful dead to warn the others.
1055 * @param $name String
1057 public function requireHook( $name ) {
1059 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1060 if( isset( $wgParser->mTagHooks[$name] ) ) {
1061 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1063 wfDie( "This test suite requires the '$name' hook extension.\n" );
1068 * Steal a callback function from the primary parser, save it for
1069 * application to our scary parser. If the hook is not installed,
1070 * die a painful dead to warn the others.
1072 * @param $name String
1074 public function requireFunctionHook( $name ) {
1076 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1077 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1078 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1080 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1085 * Run the "tidy" command on text if the $wgUseTidy
1088 * @param $text String: the text to tidy
1092 private function tidy( $text ) {
1095 $text = Parser::tidy($text);
1100 private function wellFormed( $text ) {
1102 Sanitizer::hackDocType() .
1107 $parser = xml_parser_create( "UTF-8" );
1109 # case folding violates XML standard, turn it off
1110 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1112 if( !xml_parse( $parser, $html, true ) ) {
1113 $err = xml_error_string( xml_get_error_code( $parser ) );
1114 $position = xml_get_current_byte_index( $parser );
1115 $fragment = $this->extractFragment( $html, $position );
1116 $this->mXmlError = "$err at byte $position:\n$fragment";
1117 xml_parser_free( $parser );
1120 xml_parser_free( $parser );
1124 private function extractFragment( $text, $position ) {
1125 $start = max( 0, $position - 10 );
1126 $before = $position - $start;
1128 $this->term->color( 34 ) .
1129 substr( $text, $start, $before ) .
1130 $this->term->color( 0 ) .
1131 $this->term->color( 31 ) .
1132 $this->term->color( 1 ) .
1133 substr( $text, $position, 1 ) .
1134 $this->term->color( 0 ) .
1135 $this->term->color( 34 ) .
1136 substr( $text, $position + 1, 9 ) .
1137 $this->term->color( 0 ) .
1139 $display = str_replace( "\n", ' ', $fragment );
1141 str_repeat( ' ', $before ) .
1142 $this->term->color( 31 ) .
1144 $this->term->color( 0 );
1145 return "$display\n$caret";
1149 class AnsiTermColorer {
1150 function __construct() {
1154 * Return ANSI terminal escape code for changing text attribs/color
1156 * @param $color String: semicolon-separated list of attribute/color codes
1159 public function color( $color ) {
1160 global $wgCommandLineDarkBg;
1161 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1162 return "\x1b[{$light}{$color}m";
1166 * Return ANSI terminal escape code for restoring default text attributes
1170 public function reset() {
1171 return $this->color( 0 );
1175 /* A colour-less terminal */
1176 class DummyTermColorer {
1177 public function color( $color ) {
1181 public function reset() {
1186 class TestRecorder {
1190 function __construct( $parent ) {
1191 $this->parent = $parent;
1192 $this->term = $parent->term;
1200 function record( $test, $result ) {
1202 $this->success += ($result ? 1 : 0);
1210 if( $this->total > 0 ) {
1211 $this->reportPercentage( $this->success, $this->total );
1213 wfDie( "No tests found.\n" );
1217 function reportPercentage( $success, $total ) {
1218 $ratio = wfPercent( 100 * $success / $total );
1219 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1220 if( $success == $total ) {
1221 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1223 $failed = $total - $success ;
1224 print $this->term->color( 31 ) . "$failed tests failed!";
1226 print $this->term->reset() . "\n";
1227 return ($success == $total);
1231 class DbTestPreviewer extends TestRecorder {
1232 protected $lb; ///< Database load balancer
1233 protected $db; ///< Database connection to the main DB
1234 protected $curRun; ///< run ID number for the current run
1235 protected $prevRun; ///< run ID number for the previous run, if any
1236 protected $results; ///< Result array
1239 * This should be called before the table prefix is changed
1241 function __construct( $parent ) {
1242 parent::__construct( $parent );
1243 $this->lb = wfGetLBFactory()->newMainLB();
1244 // This connection will have the wiki's table prefix, not parsertest_
1245 $this->db = $this->lb->getConnection( DB_MASTER );
1249 * Set up result recording; insert a record for the run with the date
1250 * and all that fun stuff
1256 if( ! $this->db->tableExists( 'testrun' )
1257 or ! $this->db->tableExists( 'testitem' ) )
1259 print "WARNING> `testrun` table not found in database.\n";
1260 $this->prevRun = false;
1262 // We'll make comparisons against the previous run later...
1263 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1265 $this->results = array();
1268 function record( $test, $result ) {
1269 parent::record( $test, $result );
1270 $this->results[$test] = $result;
1274 if( $this->prevRun ) {
1275 // f = fail, p = pass, n = nonexistent
1276 // codes show before then after
1278 'fp' => 'previously failing test(s) now PASSING! :)',
1279 'pn' => 'previously PASSING test(s) removed o_O',
1280 'np' => 'new PASSING test(s) :)',
1282 'pf' => 'previously passing test(s) now FAILING! :(',
1283 'fn' => 'previously FAILING test(s) removed O_o',
1284 'nf' => 'new FAILING test(s) :(',
1285 'ff' => 'still FAILING test(s) :(',
1288 $prevResults = array();
1290 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1291 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1292 foreach ( $res as $row ) {
1293 if ( !$this->parent->regex
1294 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1296 $prevResults[$row->ti_name] = $row->ti_success;
1300 $combined = array_keys( $this->results + $prevResults );
1302 # Determine breakdown by change type
1303 $breakdown = array();
1304 foreach ( $combined as $test ) {
1305 if ( !isset( $prevResults[$test] ) ) {
1307 } elseif ( $prevResults[$test] == 1 ) {
1309 } else /* if ( $prevResults[$test] == 0 )*/ {
1312 if ( !isset( $this->results[$test] ) ) {
1314 } elseif ( $this->results[$test] == 1 ) {
1316 } else /*if ( $this->results[$test] == 0 ) */ {
1319 $code = $before . $after;
1320 if ( isset( $table[$code] ) ) {
1321 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1326 foreach ( $table as $code => $label ) {
1327 if( !empty( $breakdown[$code] ) ) {
1328 $count = count($breakdown[$code]);
1329 printf( "\n%4d %s\n", $count, $label );
1330 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1331 print " * $differing_test_name [$statusInfo]\n";
1336 print "No previous test runs to compare against.\n";
1343 ** Returns a string giving information about when a test last had a status change.
1344 ** Could help to track down when regressions were introduced, as distinct from tests
1345 ** which have never passed (which are more change requests than regressions).
1347 private function getTestStatusInfo($testname, $after) {
1349 // If we're looking at a test that has just been removed, then say when it first appeared.
1350 if ( $after == 'n' ) {
1351 $changedRun = $this->db->selectField ( 'testitem',
1353 array( 'ti_name' => $testname ),
1355 $appear = $this->db->selectRow ( 'testrun',
1356 array( 'tr_date', 'tr_mw_version' ),
1357 array( 'tr_id' => $changedRun ),
1359 return "First recorded appearance: "
1360 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1361 . ", " . $appear->tr_mw_version;
1364 // Otherwise, this test has previous recorded results.
1365 // See when this test last had a different result to what we're seeing now.
1367 'ti_name' => $testname,
1368 'ti_success' => ($after == 'f' ? "1" : "0") );
1369 if ( $this->curRun ) {
1370 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1373 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1375 // If no record of ever having had a different result.
1376 if ( is_null ( $changedRun ) ) {
1377 if ($after == "f") {
1378 return "Has never passed";
1380 return "Has never failed";
1384 // Otherwise, we're looking at a test whose status has changed.
1385 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1386 // In this situation, give as much info as we can as to when it changed status.
1387 $pre = $this->db->selectRow ( 'testrun',
1388 array( 'tr_date', 'tr_mw_version' ),
1389 array( 'tr_id' => $changedRun ),
1391 $post = $this->db->selectRow ( 'testrun',
1392 array( 'tr_date', 'tr_mw_version' ),
1393 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1395 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1399 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1403 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1404 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1410 * Commit transaction and clean up for result recording
1413 $this->lb->commitMasterChanges();
1414 $this->lb->closeAll();
1420 class DbTestRecorder extends DbTestPreviewer {
1422 * Set up result recording; insert a record for the run with the date
1423 * and all that fun stuff
1426 global $wgDBtype, $options;
1429 if( ! $this->db->tableExists( 'testrun' )
1430 or ! $this->db->tableExists( 'testitem' ) )
1432 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1433 if ($wgDBtype === 'postgres')
1434 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1435 elseif ($wgDBtype === 'oracle')
1436 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1438 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1439 echo "OK, resuming.\n";
1444 $this->db->insert( 'testrun',
1446 'tr_date' => $this->db->timestamp(),
1447 'tr_mw_version' => isset( $options['setversion'] ) ?
1448 $options['setversion'] : SpecialVersion::getVersion(),
1449 'tr_php_version' => phpversion(),
1450 'tr_db_version' => $this->db->getServerVersion(),
1451 'tr_uname' => php_uname()
1454 if ($wgDBtype === 'postgres')
1455 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1457 $this->curRun = $this->db->insertId();
1461 * Record an individual test item's success or failure to the db
1463 * @param $test String
1464 * @param $result Boolean
1466 function record( $test, $result ) {
1467 parent::record( $test, $result );
1468 $this->db->insert( 'testitem',
1470 'ti_run' => $this->curRun,
1472 'ti_success' => $result ? 1 : 0,
1478 class RemoteTestRecorder extends TestRecorder {
1481 $this->results = array();
1482 $this->ping( 'running' );
1485 function record( $test, $result ) {
1486 parent::record( $test, $result );
1487 $this->results[$test] = (bool)$result;
1491 $this->ping( 'complete', $this->results );
1496 * Inform a CodeReview instance that we've started or completed a test run...
1498 * @param $status string: "running" - tell it we've started
1499 * "complete" - provide test results array
1500 * "abort" - something went horribly awry
1501 * @param $results array of test name => true/false
1503 function ping( $status, $results=false ) {
1504 global $wgParserTestRemote, $IP;
1506 $remote = $wgParserTestRemote;
1507 $revId = SpecialVersion::getSvnRevision( $IP );
1508 $jsonResults = json_encode( $results );
1511 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1515 // Generate a hash MAC to validate our credentials
1522 if( $status == "complete" ) {
1523 $message[] = $jsonResults;
1525 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1528 'action' => 'codetestupload',
1530 'repo' => $remote['repo'],
1531 'suite' => $remote['suite'],
1533 'status' => $status,
1536 if( $status == "complete" ) {
1537 $postData['results'] = $jsonResults;
1539 $response = $this->post( $remote['api-url'], $postData );
1541 if( $response === false ) {
1542 print "CodeReview info upload failed to reach server.\n";
1545 $responseData = FormatJson::decode( $response, true );
1546 if( !is_array( $responseData ) ) {
1547 print "CodeReview API response not recognized...\n";
1548 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1551 if( isset( $responseData['error'] ) ) {
1552 $code = $responseData['error']['code'];
1553 $info = $responseData['error']['info'];
1554 print "CodeReview info upload failed: $code $info\n";
1559 function post( $url, $data ) {
1560 return Http::post( $url, array( 'postData' => $data) );
1564 class TestFileIterator implements Iterator {
1573 function __construct( $file, $parser = null ) {
1576 $this->file = $file;
1577 $this->fh = fopen($this->file, "rt");
1579 wfDie( "Couldn't open file '$file'\n" );
1582 $this->parser = $parser;
1584 if( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1585 $this->lineNum = $this->index = 0;
1588 function setParser( ParserTest $parser ) {
1589 $this->parser = $parser;
1593 if(fseek($this->fh, 0)) {
1594 wfDie( "Couldn't fseek to the start of '$filename'\n" );
1604 function current() {
1609 return $this->index;
1613 if($this->readNextTest()) {
1622 return $this->eof != true;
1625 function readNextTest() {
1629 while( false !== ($line = fgets( $this->fh ) ) ) {
1632 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1633 $section = strtolower( $matches[1] );
1634 if( $section == 'endarticle') {
1635 if( !isset( $data['text'] ) ) {
1636 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
1638 if( !isset( $data['article'] ) ) {
1639 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
1641 if( $this->parser ) {
1642 $this->parser->addArticle($this->parser->chomp($data['article']), $this->parser->chomp($data['text']),
1649 if( $section == 'endhooks' ) {
1650 if( !isset( $data['hooks'] ) ) {
1651 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
1653 foreach( explode( "\n", $data['hooks'] ) as $line ) {
1654 $line = trim( $line );
1656 if( $this->parser ) $this->parser->requireHook( $line );
1663 if( $section == 'endfunctionhooks' ) {
1664 if( !isset( $data['functionhooks'] ) ) {
1665 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
1667 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
1668 $line = trim( $line );
1670 if( $this->parser ) $this->parser->requireFunctionHook( $line );
1677 if( $section == 'end' ) {
1678 if( !isset( $data['test'] ) ) {
1679 wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
1681 if( !isset( $data['input'] ) ) {
1682 wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
1684 if( !isset( $data['result'] ) ) {
1685 wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
1687 if( !isset( $data['options'] ) ) {
1688 $data['options'] = '';
1690 if (!isset( $data['config'] ) )
1691 $data['config'] = '';
1694 && ((preg_match('/\\bdisabled\\b/i', $data['options']) && !$this->parser->runDisabled)
1695 || !preg_match("/".$this->parser->regex."/i", $data['test'])) ) {
1701 if ( $this->parser &&
1702 preg_match('/\\bmath\\b/i', $data['options']) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1703 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1709 if( $this->parser ) {
1710 $this->test = array(
1711 'test' => $this->parser->chomp( $data['test'] ),
1712 'input' => $this->parser->chomp( $data['input'] ),
1713 'result' => $this->parser->chomp( $data['result'] ),
1714 'options' => $this->parser->chomp( $data['options'] ),
1715 'config' => $this->parser->chomp( $data['config'] ) );
1717 $this->test['test'] = $data['test'];
1721 if ( isset ($data[$section] ) ) {
1722 wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
1724 $data[$section] = '';
1728 $data[$section] .= $line;