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() {
308 global $wgParserConf;
309 $class = $wgParserConf['class'];
310 $parser = new $class( $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 $parser = $this->getParser();
356 $title = Title::newFromText( $titleText );
359 if( isset( $opts['pst'] ) ) {
360 $out = $parser->preSaveTransform( $input, $title, $user, $options );
361 } elseif( isset( $opts['msg'] ) ) {
362 $out = $parser->transformMsg( $input, $options );
363 } elseif( isset( $opts['section'] ) ) {
364 $section = $opts['section'];
365 $out = $parser->getSection( $input, $section );
366 } elseif( isset( $opts['replace'] ) ) {
367 $section = $opts['replace'][0];
368 $replace = $opts['replace'][1];
369 $out = $parser->replaceSection( $input, $section, $replace );
370 } elseif( isset( $opts['comment'] ) ) {
371 $linker = $user->getSkin();
372 $out = $linker->formatComment( $input, $title, $local );
373 } elseif( isset( $opts['preload'] ) ) {
374 $out = $parser->getpreloadText( $input, $title, $options );
376 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
377 $out = $output->getText();
379 if ( isset( $opts['showtitle'] ) ) {
380 if($output->getTitleText()) $title = $output->getTitleText();
381 $out = "$title\n$out";
383 if (isset( $opts['ill'] ) ) {
384 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
385 } elseif( isset( $opts['cat'] ) ) {
387 $wgOut->addCategoryLinks($output->getCategories());
388 $cats = $wgOut->getCategoryLinks();
389 if ( isset( $cats['normal'] ) ) {
390 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
396 $result = $this->tidy($result);
400 $this->teardownGlobals();
402 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
403 return $this->showSuccess( $desc );
405 return $this->showFailure( $desc, $result, $out );
411 * Use a regex to find out the value of an option
412 * @param $key String: name of option val to retrieve
413 * @param $opts Options array to look in
414 * @param $default Mixed: default value returned if not found
416 private static function getOptionValue( $key, $opts, $default ) {
417 $key = strtolower( $key );
418 if( isset( $opts[$key] ) ) {
425 private function parseOptions( $instring ) {
427 $lines = explode( "\n", $instring );
432 // foo=bar,"baz quux"
456 \[\[[^]]*\]\] # Link target
464 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
465 foreach( $matches as $bits ) {
466 $match = array_shift( $bits );
467 $key = strtolower( array_shift( $bits ) );
468 if( count( $bits ) == 0 ) {
470 } elseif( count( $bits ) == 1 ) {
471 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
474 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
481 private function cleanupOption( $opt ) {
482 if( substr( $opt, 0, 1 ) == '"' ) {
483 return substr( $opt, 1, -1 );
485 if( substr( $opt, 0, 2 ) == '[[' ) {
486 return substr( $opt, 2, -2 );
492 * Set up the global variables for a consistent environment for each test.
493 * Ideally this should replace the global configuration entirely.
495 private function setupGlobals($opts = '', $config = '') {
497 if( !isset( $this->uploadDir ) ) {
498 $this->uploadDir = $this->setupUploadDir();
501 # Find out values for some special options.
503 self::getOptionValue( 'language', $opts, 'en' );
505 self::getOptionValue( 'variant', $opts, false );
507 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
508 $linkHolderBatchSize =
509 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
512 'wgServer' => 'http://localhost',
513 'wgScript' => '/index.php',
514 'wgScriptPath' => '/',
515 'wgArticlePath' => '/wiki/$1',
516 'wgActionPaths' => array(),
517 'wgLocalFileRepo' => array(
518 'class' => 'LocalRepo',
520 'directory' => $this->uploadDir,
521 'url' => 'http://example.com/images',
523 'transformVia404' => false,
525 'wgEnableUploads' => true,
526 'wgStyleSheetPath' => '/skins',
527 'wgSitename' => 'MediaWiki',
528 'wgServerName' => 'Britney-Spears',
529 'wgLanguageCode' => $lang,
530 'wgContLanguageCode' => $lang,
531 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
532 'wgRawHtml' => isset( $opts['rawhtml'] ),
534 'wgContLang' => null,
535 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
536 'wgMaxTocLevel' => $maxtoclevel,
537 'wgCapitalLinks' => true,
538 'wgNoFollowLinks' => true,
539 'wgNoFollowDomainExceptions' => array(),
540 'wgThumbnailScriptPath' => false,
541 'wgUseImageResize' => false,
542 'wgUseTeX' => isset( $opts['math'] ),
543 'wgMathDirectory' => $this->uploadDir . '/math',
544 'wgLocaltimezone' => 'UTC',
545 'wgAllowExternalImages' => true,
546 'wgUseTidy' => false,
547 'wgDefaultLanguageVariant' => $variant,
548 'wgVariantArticlePath' => false,
549 'wgGroupPermissions' => array( '*' => array(
550 'createaccount' => true,
553 'createpage' => true,
554 'createtalk' => true,
556 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
557 'wgDefaultExternalStore' => array(),
558 'wgForeignFileRepos' => array(),
559 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
560 'wgExperimentalHtmlIds' => false,
561 'wgExternalLinkTarget' => false,
562 'wgAlwaysUseTidy' => false,
564 'wgWellFormedXml' => true,
565 'wgAllowMicrodataAttributes' => true,
569 $configLines = explode( "\n", $config );
571 foreach( $configLines as $line ) {
572 list( $var, $value ) = explode( '=', $line, 2 );
574 $settings[$var] = eval("return $value;" );
578 $this->savedGlobals = array();
579 foreach( $settings as $var => $val ) {
580 if( array_key_exists( $var, $GLOBALS ) ) {
581 $this->savedGlobals[$var] = $GLOBALS[$var];
583 $GLOBALS[$var] = $val;
585 $langObj = Language::factory( $lang );
586 $GLOBALS['wgLang'] = $langObj;
587 $GLOBALS['wgContLang'] = $langObj;
588 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
589 $GLOBALS['wgOut'] = new OutputPage;
591 MagicWord::clearCache();
594 $wgUser = new User();
598 * List of temporary tables to create, without prefix.
599 * Some of these probably aren't necessary.
601 private function listTables() {
603 $tables = array('user', 'page', 'page_restrictions',
604 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
605 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
606 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
607 'recentchanges', 'watchlist', 'math', 'interwiki',
608 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
609 'archive', 'user_groups', 'page_props', 'category'
612 if ($wgDBtype === 'mysql')
613 array_push( $tables, 'searchindex' );
615 // Allow extensions to add to the list of tables to duplicate;
616 // may be necessary if they hook into page save or other code
617 // which will require them while running tests.
618 wfRunHooks( 'ParserTestTables', array( &$tables ) );
624 * Set up a temporary set of wiki tables to work with for the tests.
625 * Currently this will only be done once per run, and any changes to
626 * the db will be visible to later tests in the run.
628 function setupDatabase() {
629 global $wgDBprefix, $wgDBtype;
630 if ( $this->databaseSetupDone ) {
633 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
634 throw new MWException( 'setupDatabase should be called before setupGlobals' );
636 $this->databaseSetupDone = true;
637 $this->oldTablePrefix = $wgDBprefix;
639 # CREATE TEMPORARY TABLE breaks if there is more than one server
640 # FIXME: r40209 makes temporary tables break even with just one server
641 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
642 if ( true || wfGetLB()->getServerCount() != 1 ) {
643 $this->useTemporaryTables = false;
646 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
648 $db = wfGetDB( DB_MASTER );
649 $tables = $this->listTables();
651 foreach ( $tables as $tbl ) {
652 # Clean up from previous aborted run. So that table escaping
653 # works correctly across DB engines, we need to change the pre-
654 # fix back and forth so tableName() works right.
655 $this->changePrefix( $this->oldTablePrefix );
656 $oldTableName = $db->tableName( $tbl );
657 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
658 $newTableName = $db->tableName( $tbl );
660 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
661 $db->query( "DROP TABLE $newTableName" );
664 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
666 if ($wgDBtype == 'oracle')
667 $db->query('BEGIN FILL_WIKI_INFO; END;');
669 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
671 # Hack: insert a few Wikipedia in-project interwiki prefixes,
672 # for testing inter-language links
673 $db->insert( 'interwiki', array(
674 array( 'iw_prefix' => 'wikipedia',
675 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
677 array( 'iw_prefix' => 'meatball',
678 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
680 array( 'iw_prefix' => 'zh',
681 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
683 array( 'iw_prefix' => 'es',
684 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
686 array( 'iw_prefix' => 'fr',
687 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
689 array( 'iw_prefix' => 'ru',
690 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
695 if ($wgDBtype == 'oracle') {
696 # Insert 0 and 1 user_ids to prevent FK violations
699 $db->insert( 'user', array(
701 'user_name' => 'Anonymous') );
703 # Hack-on-Hack: Insert a test user to be able to insert an image
704 $db->insert( 'user', array(
706 'user_name' => 'Tester') );
709 # Hack: Insert an image to work with
710 $db->insert( 'image', array(
711 'img_name' => 'Foobar.jpg',
713 'img_description' => 'Some lame file',
715 'img_user_text' => 'WikiSysop',
716 'img_timestamp' => $db->timestamp( '20010115123500' ),
720 'img_media_type' => MEDIATYPE_BITMAP,
721 'img_major_mime' => "image",
722 'img_minor_mime' => "jpeg",
723 'img_metadata' => serialize( array() ),
726 # This image will be blacklisted in [[MediaWiki:Bad image list]]
727 $db->insert( 'image', array(
728 'img_name' => 'Bad.jpg',
730 'img_description' => 'zomgnotcensored',
732 'img_user_text' => 'WikiSysop',
733 'img_timestamp' => $db->timestamp( '20010115123500' ),
737 'img_media_type' => MEDIATYPE_BITMAP,
738 'img_major_mime' => "image",
739 'img_minor_mime' => "jpeg",
740 'img_metadata' => serialize( array() ),
743 # Update certain things in site_stats
744 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
746 # Reinitialise the LocalisationCache to match the database state
747 Language::getLocalisationCache()->unloadAll();
749 # Make a new message cache
750 global $wgMessageCache, $wgMemc;
751 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
755 * Change the table prefix on all open DB connections/
757 protected function changePrefix( $prefix ) {
759 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
760 $wgDBprefix = $prefix;
763 public function changeLBPrefix( $lb, $prefix ) {
764 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
767 public function changeDBPrefix( $db, $prefix ) {
768 $db->tablePrefix( $prefix );
771 private function teardownDatabase() {
773 if ( !$this->databaseSetupDone ) {
776 $this->changePrefix( $this->oldTablePrefix );
777 $this->databaseSetupDone = false;
778 if ( $this->useTemporaryTables ) {
779 # Don't need to do anything
784 $tables = $this->listTables();
785 $db = wfGetDB( DB_MASTER );
786 foreach ( $tables as $table ) {
787 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
790 if ($wgDBtype == 'oracle')
791 $db->query('BEGIN FILL_WIKI_INFO; END;');
796 * Create a dummy uploads directory which will contain a couple
797 * of files in order to pass existence tests.
799 * @return String: the directory
801 private function setupUploadDir() {
803 if ( $this->keepUploads ) {
804 $dir = wfTempDir() . '/mwParser-images';
805 if ( is_dir( $dir ) ) {
809 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
812 wfDebug( "Creating upload directory $dir\n" );
813 if ( file_exists( $dir ) ) {
814 wfDebug( "Already exists!\n" );
817 wfMkdirParents( $dir . '/3/3a' );
818 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
820 wfMkdirParents( $dir . '/0/09' );
821 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
826 * Restore default values and perform any necessary clean-up
827 * after each test runs.
829 private function teardownGlobals() {
830 RepoGroup::destroySingleton();
831 LinkCache::singleton()->clear();
832 foreach( $this->savedGlobals as $var => $val ) {
833 $GLOBALS[$var] = $val;
835 if( isset( $this->uploadDir ) ) {
836 $this->teardownUploadDir( $this->uploadDir );
837 unset( $this->uploadDir );
842 * Remove the dummy uploads directory
844 private function teardownUploadDir( $dir ) {
845 if ( $this->keepUploads ) {
849 // delete the files first, then the dirs.
852 "$dir/3/3a/Foobar.jpg",
853 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
854 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
855 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
856 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
860 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
870 "$dir/thumb/3/3a/Foobar.jpg",
887 * Delete the specified files, if they exist.
888 * @param $files Array: full paths to files to delete.
890 private static function deleteFiles( $files ) {
891 foreach( $files as $file ) {
892 if( file_exists( $file ) ) {
899 * Delete the specified directories, if they exist. Must be empty.
900 * @param $dirs Array: full paths to directories to delete.
902 private static function deleteDirs( $dirs ) {
903 foreach( $dirs as $dir ) {
904 if( is_dir( $dir ) ) {
911 * "Running test $desc..."
913 protected function showTesting( $desc ) {
914 print "Running test $desc... ";
918 * Print a happy success message.
920 * @param $desc String: the test name
923 protected function showSuccess( $desc ) {
924 if( $this->showProgress ) {
925 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
931 * Print a failure message and provide some explanatory output
932 * about what went wrong if so configured.
934 * @param $desc String: the test name
935 * @param $result String: expected HTML output
936 * @param $html String: actual HTML output
939 protected function showFailure( $desc, $result, $html ) {
940 if( $this->showFailure ) {
941 if( !$this->showProgress ) {
942 # In quiet mode we didn't show the 'Testing' message before the
943 # test, in case it succeeded. Show it now:
944 $this->showTesting( $desc );
946 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
947 if ( $this->showOutput ) {
948 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
950 if( $this->showDiffs ) {
951 print $this->quickDiff( $result, $html );
952 if( !$this->wellFormed( $html ) ) {
953 print "XML error: $this->mXmlError\n";
961 * Run given strings through a diff and return the (colorized) output.
962 * Requires writable /tmp directory and a 'diff' command in the PATH.
964 * @param $input String
965 * @param $output String
966 * @param $inFileTail String: tailing for the input file name
967 * @param $outFileTail String: tailing for the output file name
970 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
971 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
973 $infile = "$prefix-$inFileTail";
974 $this->dumpToFile( $input, $infile );
976 $outfile = "$prefix-$outFileTail";
977 $this->dumpToFile( $output, $outfile );
979 $diff = `diff -au $infile $outfile`;
983 return $this->colorDiff( $diff );
987 * Write the given string to a file, adding a final newline.
989 * @param $data String
990 * @param $filename String
992 private function dumpToFile( $data, $filename ) {
993 $file = fopen( $filename, "wt" );
994 fwrite( $file, $data . "\n" );
999 * Colorize unified diff output if set for ANSI color output.
1000 * Subtractions are colored blue, additions red.
1002 * @param $text String
1005 protected function colorDiff( $text ) {
1006 return preg_replace(
1007 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1008 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1009 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1014 * Show "Reading tests from ..."
1016 * @param $path String
1018 public function showRunFile( $path ){
1019 print $this->term->color( 1 ) .
1020 "Reading tests from \"$path\"..." .
1021 $this->term->reset() .
1026 * Insert a temporary test article
1027 * @param $name String: the title, including any prefix
1028 * @param $text String: the article text
1029 * @param $line Integer: the input line number, for reporting errors
1031 public function addArticle($name, $text, $line) {
1032 $this->setupGlobals();
1033 $title = Title::newFromText( $name );
1034 if ( is_null($title) ) {
1035 wfDie( "invalid title at line $line\n" );
1038 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1040 wfDie( "duplicate article '$name' at line $line\n" );
1043 $art = new Article($title);
1044 $art->insertNewArticle($text, '', false, false );
1046 $this->teardownGlobals();
1050 * Steal a callback function from the primary parser, save it for
1051 * application to our scary parser. If the hook is not installed,
1052 * die a painful dead to warn the others.
1054 * @param $name String
1056 public function requireHook( $name ) {
1058 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1059 if( isset( $wgParser->mTagHooks[$name] ) ) {
1060 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1062 wfDie( "This test suite requires the '$name' hook extension.\n" );
1067 * Steal a callback function from the primary parser, save it for
1068 * application to our scary parser. If the hook is not installed,
1069 * die a painful dead to warn the others.
1071 * @param $name String
1073 public function requireFunctionHook( $name ) {
1075 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1076 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1077 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1079 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1084 * Run the "tidy" command on text if the $wgUseTidy
1087 * @param $text String: the text to tidy
1091 private function tidy( $text ) {
1094 $text = Parser::tidy($text);
1099 private function wellFormed( $text ) {
1101 Sanitizer::hackDocType() .
1106 $parser = xml_parser_create( "UTF-8" );
1108 # case folding violates XML standard, turn it off
1109 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1111 if( !xml_parse( $parser, $html, true ) ) {
1112 $err = xml_error_string( xml_get_error_code( $parser ) );
1113 $position = xml_get_current_byte_index( $parser );
1114 $fragment = $this->extractFragment( $html, $position );
1115 $this->mXmlError = "$err at byte $position:\n$fragment";
1116 xml_parser_free( $parser );
1119 xml_parser_free( $parser );
1123 private function extractFragment( $text, $position ) {
1124 $start = max( 0, $position - 10 );
1125 $before = $position - $start;
1127 $this->term->color( 34 ) .
1128 substr( $text, $start, $before ) .
1129 $this->term->color( 0 ) .
1130 $this->term->color( 31 ) .
1131 $this->term->color( 1 ) .
1132 substr( $text, $position, 1 ) .
1133 $this->term->color( 0 ) .
1134 $this->term->color( 34 ) .
1135 substr( $text, $position + 1, 9 ) .
1136 $this->term->color( 0 ) .
1138 $display = str_replace( "\n", ' ', $fragment );
1140 str_repeat( ' ', $before ) .
1141 $this->term->color( 31 ) .
1143 $this->term->color( 0 );
1144 return "$display\n$caret";
1148 class AnsiTermColorer {
1149 function __construct() {
1153 * Return ANSI terminal escape code for changing text attribs/color
1155 * @param $color String: semicolon-separated list of attribute/color codes
1158 public function color( $color ) {
1159 global $wgCommandLineDarkBg;
1160 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1161 return "\x1b[{$light}{$color}m";
1165 * Return ANSI terminal escape code for restoring default text attributes
1169 public function reset() {
1170 return $this->color( 0 );
1174 /* A colour-less terminal */
1175 class DummyTermColorer {
1176 public function color( $color ) {
1180 public function reset() {
1185 class TestRecorder {
1189 function __construct( $parent ) {
1190 $this->parent = $parent;
1191 $this->term = $parent->term;
1199 function record( $test, $result ) {
1201 $this->success += ($result ? 1 : 0);
1209 if( $this->total > 0 ) {
1210 $this->reportPercentage( $this->success, $this->total );
1212 wfDie( "No tests found.\n" );
1216 function reportPercentage( $success, $total ) {
1217 $ratio = wfPercent( 100 * $success / $total );
1218 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1219 if( $success == $total ) {
1220 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1222 $failed = $total - $success ;
1223 print $this->term->color( 31 ) . "$failed tests failed!";
1225 print $this->term->reset() . "\n";
1226 return ($success == $total);
1230 class DbTestPreviewer extends TestRecorder {
1231 protected $lb; ///< Database load balancer
1232 protected $db; ///< Database connection to the main DB
1233 protected $curRun; ///< run ID number for the current run
1234 protected $prevRun; ///< run ID number for the previous run, if any
1235 protected $results; ///< Result array
1238 * This should be called before the table prefix is changed
1240 function __construct( $parent ) {
1241 parent::__construct( $parent );
1242 $this->lb = wfGetLBFactory()->newMainLB();
1243 // This connection will have the wiki's table prefix, not parsertest_
1244 $this->db = $this->lb->getConnection( DB_MASTER );
1248 * Set up result recording; insert a record for the run with the date
1249 * and all that fun stuff
1255 if( ! $this->db->tableExists( 'testrun' )
1256 or ! $this->db->tableExists( 'testitem' ) )
1258 print "WARNING> `testrun` table not found in database.\n";
1259 $this->prevRun = false;
1261 // We'll make comparisons against the previous run later...
1262 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1264 $this->results = array();
1267 function record( $test, $result ) {
1268 parent::record( $test, $result );
1269 $this->results[$test] = $result;
1273 if( $this->prevRun ) {
1274 // f = fail, p = pass, n = nonexistent
1275 // codes show before then after
1277 'fp' => 'previously failing test(s) now PASSING! :)',
1278 'pn' => 'previously PASSING test(s) removed o_O',
1279 'np' => 'new PASSING test(s) :)',
1281 'pf' => 'previously passing test(s) now FAILING! :(',
1282 'fn' => 'previously FAILING test(s) removed O_o',
1283 'nf' => 'new FAILING test(s) :(',
1284 'ff' => 'still FAILING test(s) :(',
1287 $prevResults = array();
1289 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1290 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1291 foreach ( $res as $row ) {
1292 if ( !$this->parent->regex
1293 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1295 $prevResults[$row->ti_name] = $row->ti_success;
1299 $combined = array_keys( $this->results + $prevResults );
1301 # Determine breakdown by change type
1302 $breakdown = array();
1303 foreach ( $combined as $test ) {
1304 if ( !isset( $prevResults[$test] ) ) {
1306 } elseif ( $prevResults[$test] == 1 ) {
1308 } else /* if ( $prevResults[$test] == 0 )*/ {
1311 if ( !isset( $this->results[$test] ) ) {
1313 } elseif ( $this->results[$test] == 1 ) {
1315 } else /*if ( $this->results[$test] == 0 ) */ {
1318 $code = $before . $after;
1319 if ( isset( $table[$code] ) ) {
1320 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1325 foreach ( $table as $code => $label ) {
1326 if( !empty( $breakdown[$code] ) ) {
1327 $count = count($breakdown[$code]);
1328 printf( "\n%4d %s\n", $count, $label );
1329 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1330 print " * $differing_test_name [$statusInfo]\n";
1335 print "No previous test runs to compare against.\n";
1342 ** Returns a string giving information about when a test last had a status change.
1343 ** Could help to track down when regressions were introduced, as distinct from tests
1344 ** which have never passed (which are more change requests than regressions).
1346 private function getTestStatusInfo($testname, $after) {
1348 // If we're looking at a test that has just been removed, then say when it first appeared.
1349 if ( $after == 'n' ) {
1350 $changedRun = $this->db->selectField ( 'testitem',
1352 array( 'ti_name' => $testname ),
1354 $appear = $this->db->selectRow ( 'testrun',
1355 array( 'tr_date', 'tr_mw_version' ),
1356 array( 'tr_id' => $changedRun ),
1358 return "First recorded appearance: "
1359 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1360 . ", " . $appear->tr_mw_version;
1363 // Otherwise, this test has previous recorded results.
1364 // See when this test last had a different result to what we're seeing now.
1366 'ti_name' => $testname,
1367 'ti_success' => ($after == 'f' ? "1" : "0") );
1368 if ( $this->curRun ) {
1369 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1372 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1374 // If no record of ever having had a different result.
1375 if ( is_null ( $changedRun ) ) {
1376 if ($after == "f") {
1377 return "Has never passed";
1379 return "Has never failed";
1383 // Otherwise, we're looking at a test whose status has changed.
1384 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1385 // In this situation, give as much info as we can as to when it changed status.
1386 $pre = $this->db->selectRow ( 'testrun',
1387 array( 'tr_date', 'tr_mw_version' ),
1388 array( 'tr_id' => $changedRun ),
1390 $post = $this->db->selectRow ( 'testrun',
1391 array( 'tr_date', 'tr_mw_version' ),
1392 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1394 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1398 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1402 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1403 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1409 * Commit transaction and clean up for result recording
1412 $this->lb->commitMasterChanges();
1413 $this->lb->closeAll();
1419 class DbTestRecorder extends DbTestPreviewer {
1421 * Set up result recording; insert a record for the run with the date
1422 * and all that fun stuff
1425 global $wgDBtype, $options;
1428 if( ! $this->db->tableExists( 'testrun' )
1429 or ! $this->db->tableExists( 'testitem' ) )
1431 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1432 if ($wgDBtype === 'postgres')
1433 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1434 elseif ($wgDBtype === 'oracle')
1435 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1437 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1438 echo "OK, resuming.\n";
1443 $this->db->insert( 'testrun',
1445 'tr_date' => $this->db->timestamp(),
1446 'tr_mw_version' => isset( $options['setversion'] ) ?
1447 $options['setversion'] : SpecialVersion::getVersion(),
1448 'tr_php_version' => phpversion(),
1449 'tr_db_version' => $this->db->getServerVersion(),
1450 'tr_uname' => php_uname()
1453 if ($wgDBtype === 'postgres')
1454 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1456 $this->curRun = $this->db->insertId();
1460 * Record an individual test item's success or failure to the db
1462 * @param $test String
1463 * @param $result Boolean
1465 function record( $test, $result ) {
1466 parent::record( $test, $result );
1467 $this->db->insert( 'testitem',
1469 'ti_run' => $this->curRun,
1471 'ti_success' => $result ? 1 : 0,
1477 class RemoteTestRecorder extends TestRecorder {
1480 $this->results = array();
1481 $this->ping( 'running' );
1484 function record( $test, $result ) {
1485 parent::record( $test, $result );
1486 $this->results[$test] = (bool)$result;
1490 $this->ping( 'complete', $this->results );
1495 * Inform a CodeReview instance that we've started or completed a test run...
1497 * @param $status string: "running" - tell it we've started
1498 * "complete" - provide test results array
1499 * "abort" - something went horribly awry
1500 * @param $results array of test name => true/false
1502 function ping( $status, $results=false ) {
1503 global $wgParserTestRemote, $IP;
1505 $remote = $wgParserTestRemote;
1506 $revId = SpecialVersion::getSvnRevision( $IP );
1507 $jsonResults = json_encode( $results );
1510 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1514 // Generate a hash MAC to validate our credentials
1521 if( $status == "complete" ) {
1522 $message[] = $jsonResults;
1524 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1527 'action' => 'codetestupload',
1529 'repo' => $remote['repo'],
1530 'suite' => $remote['suite'],
1532 'status' => $status,
1535 if( $status == "complete" ) {
1536 $postData['results'] = $jsonResults;
1538 $response = $this->post( $remote['api-url'], $postData );
1540 if( $response === false ) {
1541 print "CodeReview info upload failed to reach server.\n";
1544 $responseData = json_decode( $response, true );
1545 if( !is_array( $responseData ) ) {
1546 print "CodeReview API response not recognized...\n";
1547 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1550 if( isset( $responseData['error'] ) ) {
1551 $code = $responseData['error']['code'];
1552 $info = $responseData['error']['info'];
1553 print "CodeReview info upload failed: $code $info\n";
1558 function post( $url, $data ) {
1559 return Http::post( $url, array( 'postData' => $data) );
1563 class TestFileIterator implements Iterator {
1572 function __construct( $file, $parser = null ) {
1575 $this->file = $file;
1576 $this->fh = fopen($this->file, "rt");
1578 wfDie( "Couldn't open file '$file'\n" );
1581 $this->parser = $parser;
1583 if( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1584 $this->lineNum = $this->index = 0;
1587 function setParser( ParserTest $parser ) {
1588 $this->parser = $parser;
1592 if(fseek($this->fh, 0)) {
1593 wfDie( "Couldn't fseek to the start of '$filename'\n" );
1598 $this->readNextTest();
1603 function current() {
1608 return $this->index;
1612 if($this->readNextTest()) {
1621 return $this->eof != true;
1624 function readNextTest() {
1628 while( false !== ($line = fgets( $this->fh ) ) ) {
1631 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1632 $section = strtolower( $matches[1] );
1633 if( $section == 'endarticle') {
1634 if( !isset( $data['text'] ) ) {
1635 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
1637 if( !isset( $data['article'] ) ) {
1638 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
1640 if( $this->parser ) $this->parser->addArticle($this->parser->chomp($data['article']), $this->parser->chomp($data['text']),
1646 if( $section == 'endhooks' ) {
1647 if( !isset( $data['hooks'] ) ) {
1648 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
1650 foreach( explode( "\n", $data['hooks'] ) as $line ) {
1651 $line = trim( $line );
1653 if( $this->parser ) $this->parser->requireHook( $line );
1660 if( $section == 'endfunctionhooks' ) {
1661 if( !isset( $data['functionhooks'] ) ) {
1662 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
1664 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
1665 $line = trim( $line );
1667 if( $this->parser ) $this->parser->requireFunctionHook( $line );
1674 if( $section == 'end' ) {
1675 if( !isset( $data['test'] ) ) {
1676 wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
1678 if( !isset( $data['input'] ) ) {
1679 wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
1681 if( !isset( $data['result'] ) ) {
1682 wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
1684 if( !isset( $data['options'] ) ) {
1685 $data['options'] = '';
1687 if (!isset( $data['config'] ) )
1688 $data['config'] = '';
1690 if ( $this->parser && (preg_match('/\\bdisabled\\b/i', $data['options'])
1691 || !preg_match("/{$this->parser->regex}/i", $data['test'])) && !$this->parser->runDisabled ) {
1697 if ( $this->parser &&
1698 preg_match('/\\bmath\\b/i', $data['options']) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1699 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1705 if( $this->parser ) {
1706 $this->test = array(
1707 'test' => $this->parser->chomp( $data['test'] ),
1708 'input' => $this->parser->chomp( $data['input'] ),
1709 'result' => $this->parser->chomp( $data['result'] ),
1710 'options' => $this->parser->chomp( $data['options'] ),
1711 'config' => $this->parser->chomp( $data['config'] ) );
1713 $this->test['test'] = $data['test'];
1717 if ( isset ($data[$section] ) ) {
1718 wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
1720 $data[$section] = '';
1724 $data[$section] .= $line;