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,
559 'wgAllowDisplayTitle' => true,
560 'wgRestrictDisplayTitle' => false,
564 $configLines = explode( "\n", $config );
566 foreach( $configLines as $line ) {
567 list( $var, $value ) = explode( '=', $line, 2 );
569 $settings[$var] = eval("return $value;" );
573 $this->savedGlobals = array();
574 foreach( $settings as $var => $val ) {
575 if( array_key_exists( $var, $GLOBALS ) ) {
576 $this->savedGlobals[$var] = $GLOBALS[$var];
578 $GLOBALS[$var] = $val;
580 $langObj = Language::factory( $lang );
581 $GLOBALS['wgLang'] = $langObj;
582 $GLOBALS['wgContLang'] = $langObj;
583 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
584 $GLOBALS['wgOut'] = new OutputPage;
586 MagicWord::clearCache();
589 $wgUser = new User();
593 * List of temporary tables to create, without prefix.
594 * Some of these probably aren't necessary.
596 private function listTables() {
598 $tables = array('user', 'page', 'page_restrictions',
599 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
600 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
601 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
602 'recentchanges', 'watchlist', 'math', 'interwiki',
603 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
604 'archive', 'user_groups', 'page_props', 'category'
607 if ($wgDBtype === 'mysql')
608 array_push( $tables, 'searchindex' );
610 // Allow extensions to add to the list of tables to duplicate;
611 // may be necessary if they hook into page save or other code
612 // which will require them while running tests.
613 wfRunHooks( 'ParserTestTables', array( &$tables ) );
619 * Set up a temporary set of wiki tables to work with for the tests.
620 * Currently this will only be done once per run, and any changes to
621 * the db will be visible to later tests in the run.
623 function setupDatabase() {
624 global $wgDBprefix, $wgDBtype;
625 if ( $this->databaseSetupDone ) {
628 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
629 throw new MWException( 'setupDatabase should be called before setupGlobals' );
631 $this->databaseSetupDone = true;
632 $this->oldTablePrefix = $wgDBprefix;
634 # CREATE TEMPORARY TABLE breaks if there is more than one server
635 # FIXME: r40209 makes temporary tables break even with just one server
636 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
637 if ( true || wfGetLB()->getServerCount() != 1 ) {
638 $this->useTemporaryTables = false;
641 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
643 $db = wfGetDB( DB_MASTER );
644 $tables = $this->listTables();
646 foreach ( $tables as $tbl ) {
647 # Clean up from previous aborted run. So that table escaping
648 # works correctly across DB engines, we need to change the pre-
649 # fix back and forth so tableName() works right.
650 $this->changePrefix( $this->oldTablePrefix );
651 $oldTableName = $db->tableName( $tbl );
652 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
653 $newTableName = $db->tableName( $tbl );
655 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
656 $db->query( "DROP TABLE $newTableName" );
659 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
661 if ($wgDBtype == 'oracle')
662 $db->query('BEGIN FILL_WIKI_INFO; END;');
664 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
666 # Hack: insert a few Wikipedia in-project interwiki prefixes,
667 # for testing inter-language links
668 $db->insert( 'interwiki', array(
669 array( 'iw_prefix' => 'wikipedia',
670 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
672 array( 'iw_prefix' => 'meatball',
673 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
675 array( 'iw_prefix' => 'zh',
676 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
678 array( 'iw_prefix' => 'es',
679 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
681 array( 'iw_prefix' => 'fr',
682 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
684 array( 'iw_prefix' => 'ru',
685 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
690 if ($wgDBtype == 'oracle') {
691 # Insert 0 and 1 user_ids to prevent FK violations
694 $db->insert( 'user', array(
696 'user_name' => 'Anonymous') );
698 # Hack-on-Hack: Insert a test user to be able to insert an image
699 $db->insert( 'user', array(
701 'user_name' => 'Tester') );
704 # Hack: Insert an image to work with
705 $db->insert( 'image', array(
706 'img_name' => 'Foobar.jpg',
708 'img_description' => 'Some lame file',
710 'img_user_text' => 'WikiSysop',
711 'img_timestamp' => $db->timestamp( '20010115123500' ),
715 'img_media_type' => MEDIATYPE_BITMAP,
716 'img_major_mime' => "image",
717 'img_minor_mime' => "jpeg",
718 'img_metadata' => serialize( array() ),
721 # This image will be blacklisted in [[MediaWiki:Bad image list]]
722 $db->insert( 'image', array(
723 'img_name' => 'Bad.jpg',
725 'img_description' => 'zomgnotcensored',
727 'img_user_text' => 'WikiSysop',
728 'img_timestamp' => $db->timestamp( '20010115123500' ),
732 'img_media_type' => MEDIATYPE_BITMAP,
733 'img_major_mime' => "image",
734 'img_minor_mime' => "jpeg",
735 'img_metadata' => serialize( array() ),
738 # Update certain things in site_stats
739 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
741 # Reinitialise the LocalisationCache to match the database state
742 Language::getLocalisationCache()->unloadAll();
744 # Make a new message cache
745 global $wgMessageCache, $wgMemc;
746 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
750 * Change the table prefix on all open DB connections/
752 protected function changePrefix( $prefix ) {
754 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
755 $wgDBprefix = $prefix;
758 public function changeLBPrefix( $lb, $prefix ) {
759 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
762 public function changeDBPrefix( $db, $prefix ) {
763 $db->tablePrefix( $prefix );
766 private function teardownDatabase() {
767 global $wgDBprefix, $wgDBtype;
768 if ( !$this->databaseSetupDone ) {
771 $this->changePrefix( $this->oldTablePrefix );
772 $this->databaseSetupDone = false;
773 if ( $this->useTemporaryTables ) {
774 # Don't need to do anything
779 $tables = $this->listTables();
780 $db = wfGetDB( DB_MASTER );
781 foreach ( $tables as $table ) {
782 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
785 if ($wgDBtype == 'oracle')
786 $db->query('BEGIN FILL_WIKI_INFO; END;');
791 * Create a dummy uploads directory which will contain a couple
792 * of files in order to pass existence tests.
793 * @return string The directory
795 private function setupUploadDir() {
797 if ( $this->keepUploads ) {
798 $dir = wfTempDir() . '/mwParser-images';
799 if ( is_dir( $dir ) ) {
803 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
806 wfDebug( "Creating upload directory $dir\n" );
807 if ( file_exists( $dir ) ) {
808 wfDebug( "Already exists!\n" );
811 wfMkdirParents( $dir . '/3/3a' );
812 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
814 wfMkdirParents( $dir . '/0/09' );
815 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
820 * Restore default values and perform any necessary clean-up
821 * after each test runs.
823 private function teardownGlobals() {
824 RepoGroup::destroySingleton();
825 LinkCache::singleton()->clear();
826 foreach( $this->savedGlobals as $var => $val ) {
827 $GLOBALS[$var] = $val;
829 if( isset( $this->uploadDir ) ) {
830 $this->teardownUploadDir( $this->uploadDir );
831 unset( $this->uploadDir );
836 * Remove the dummy uploads directory
838 private function teardownUploadDir( $dir ) {
839 if ( $this->keepUploads ) {
843 // delete the files first, then the dirs.
846 "$dir/3/3a/Foobar.jpg",
847 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
848 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
849 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
850 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
854 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
864 "$dir/thumb/3/3a/Foobar.jpg",
881 * Delete the specified files, if they exist.
882 * @param array $files full paths to files to delete.
884 private static function deleteFiles( $files ) {
885 foreach( $files as $file ) {
886 if( file_exists( $file ) ) {
893 * Delete the specified directories, if they exist. Must be empty.
894 * @param array $dirs full paths to directories to delete.
896 private static function deleteDirs( $dirs ) {
897 foreach( $dirs as $dir ) {
898 if( is_dir( $dir ) ) {
905 * "Running test $desc..."
907 protected function showTesting( $desc ) {
908 print "Running test $desc... ";
912 * Print a happy success message.
914 * @param string $desc The test name
917 protected function showSuccess( $desc ) {
918 if( $this->showProgress ) {
919 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
925 * Print a failure message and provide some explanatory output
926 * about what went wrong if so configured.
928 * @param string $desc The test name
929 * @param string $result Expected HTML output
930 * @param string $html Actual HTML output
933 protected function showFailure( $desc, $result, $html ) {
934 if( $this->showFailure ) {
935 if( !$this->showProgress ) {
936 # In quiet mode we didn't show the 'Testing' message before the
937 # test, in case it succeeded. Show it now:
938 $this->showTesting( $desc );
940 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
941 if ( $this->showOutput ) {
942 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
944 if( $this->showDiffs ) {
945 print $this->quickDiff( $result, $html );
946 if( !$this->wellFormed( $html ) ) {
947 print "XML error: $this->mXmlError\n";
955 * Run given strings through a diff and return the (colorized) output.
956 * Requires writable /tmp directory and a 'diff' command in the PATH.
958 * @param string $input
959 * @param string $output
960 * @param string $inFileTail Tailing for the input file name
961 * @param string $outFileTail Tailing for the output file name
964 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
965 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
967 $infile = "$prefix-$inFileTail";
968 $this->dumpToFile( $input, $infile );
970 $outfile = "$prefix-$outFileTail";
971 $this->dumpToFile( $output, $outfile );
973 $diff = `diff -au $infile $outfile`;
977 return $this->colorDiff( $diff );
981 * Write the given string to a file, adding a final newline.
983 * @param string $data
984 * @param string $filename
986 private function dumpToFile( $data, $filename ) {
987 $file = fopen( $filename, "wt" );
988 fwrite( $file, $data . "\n" );
993 * Colorize unified diff output if set for ANSI color output.
994 * Subtractions are colored blue, additions red.
996 * @param string $text
999 protected function colorDiff( $text ) {
1000 return preg_replace(
1001 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1002 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1003 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1008 * Show "Reading tests from ..."
1010 * @param String $path
1012 public function showRunFile( $path ){
1013 print $this->term->color( 1 ) .
1014 "Reading tests from \"$path\"..." .
1015 $this->term->reset() .
1020 * Insert a temporary test article
1021 * @param string $name the title, including any prefix
1022 * @param string $text the article text
1023 * @param int $line the input line number, for reporting errors
1025 public function addArticle($name, $text, $line) {
1026 $this->setupGlobals();
1027 $title = Title::newFromText( $name );
1028 if ( is_null($title) ) {
1029 wfDie( "invalid title at line $line\n" );
1032 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1034 wfDie( "duplicate article '$name' at line $line\n" );
1037 $art = new Article($title);
1038 $art->insertNewArticle($text, '', false, false );
1040 $this->teardownGlobals();
1044 * Steal a callback function from the primary parser, save it for
1045 * application to our scary parser. If the hook is not installed,
1046 * die a painful dead to warn the others.
1047 * @param string $name
1049 public function requireHook( $name ) {
1051 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1052 if( isset( $wgParser->mTagHooks[$name] ) ) {
1053 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1055 wfDie( "This test suite requires the '$name' hook extension.\n" );
1060 * Steal a callback function from the primary parser, save it for
1061 * application to our scary parser. If the hook is not installed,
1062 * die a painful dead to warn the others.
1063 * @param string $name
1065 private function requireFunctionHook( $name ) {
1067 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1068 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1069 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1071 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1076 * Run the "tidy" command on text if the $wgUseTidy
1079 * @param string $text the text to tidy
1083 private function tidy( $text ) {
1086 $text = Parser::tidy($text);
1091 private function wellFormed( $text ) {
1093 Sanitizer::hackDocType() .
1098 $parser = xml_parser_create( "UTF-8" );
1100 # case folding violates XML standard, turn it off
1101 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1103 if( !xml_parse( $parser, $html, true ) ) {
1104 $err = xml_error_string( xml_get_error_code( $parser ) );
1105 $position = xml_get_current_byte_index( $parser );
1106 $fragment = $this->extractFragment( $html, $position );
1107 $this->mXmlError = "$err at byte $position:\n$fragment";
1108 xml_parser_free( $parser );
1111 xml_parser_free( $parser );
1115 private function extractFragment( $text, $position ) {
1116 $start = max( 0, $position - 10 );
1117 $before = $position - $start;
1119 $this->term->color( 34 ) .
1120 substr( $text, $start, $before ) .
1121 $this->term->color( 0 ) .
1122 $this->term->color( 31 ) .
1123 $this->term->color( 1 ) .
1124 substr( $text, $position, 1 ) .
1125 $this->term->color( 0 ) .
1126 $this->term->color( 34 ) .
1127 substr( $text, $position + 1, 9 ) .
1128 $this->term->color( 0 ) .
1130 $display = str_replace( "\n", ' ', $fragment );
1132 str_repeat( ' ', $before ) .
1133 $this->term->color( 31 ) .
1135 $this->term->color( 0 );
1136 return "$display\n$caret";
1140 class AnsiTermColorer {
1141 function __construct() {
1145 * Return ANSI terminal escape code for changing text attribs/color
1147 * @param string $color Semicolon-separated list of attribute/color codes
1150 public function color( $color ) {
1151 global $wgCommandLineDarkBg;
1152 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1153 return "\x1b[{$light}{$color}m";
1157 * Return ANSI terminal escape code for restoring default text attributes
1161 public function reset() {
1162 return $this->color( 0 );
1166 /* A colour-less terminal */
1167 class DummyTermColorer {
1168 public function color( $color ) {
1172 public function reset() {
1177 class TestRecorder {
1181 function __construct( $parent ) {
1182 $this->parent = $parent;
1183 $this->term = $parent->term;
1191 function record( $test, $result ) {
1193 $this->success += ($result ? 1 : 0);
1201 if( $this->total > 0 ) {
1202 $this->reportPercentage( $this->success, $this->total );
1204 wfDie( "No tests found.\n" );
1208 function reportPercentage( $success, $total ) {
1209 $ratio = wfPercent( 100 * $success / $total );
1210 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1211 if( $success == $total ) {
1212 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1214 $failed = $total - $success ;
1215 print $this->term->color( 31 ) . "$failed tests failed!";
1217 print $this->term->reset() . "\n";
1218 return ($success == $total);
1222 class DbTestPreviewer extends TestRecorder {
1223 protected $lb; ///< Database load balancer
1224 protected $db; ///< Database connection to the main DB
1225 protected $curRun; ///< run ID number for the current run
1226 protected $prevRun; ///< run ID number for the previous run, if any
1227 protected $results; ///< Result array
1230 * This should be called before the table prefix is changed
1232 function __construct( $parent ) {
1233 parent::__construct( $parent );
1234 $this->lb = wfGetLBFactory()->newMainLB();
1235 // This connection will have the wiki's table prefix, not parsertest_
1236 $this->db = $this->lb->getConnection( DB_MASTER );
1240 * Set up result recording; insert a record for the run with the date
1241 * and all that fun stuff
1244 global $wgDBtype, $wgDBprefix;
1247 if( ! $this->db->tableExists( 'testrun' )
1248 or ! $this->db->tableExists( 'testitem' ) )
1250 print "WARNING> `testrun` table not found in database.\n";
1251 $this->prevRun = false;
1253 // We'll make comparisons against the previous run later...
1254 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1256 $this->results = array();
1259 function record( $test, $result ) {
1260 parent::record( $test, $result );
1261 $this->results[$test] = $result;
1265 if( $this->prevRun ) {
1266 // f = fail, p = pass, n = nonexistent
1267 // codes show before then after
1269 'fp' => 'previously failing test(s) now PASSING! :)',
1270 'pn' => 'previously PASSING test(s) removed o_O',
1271 'np' => 'new PASSING test(s) :)',
1273 'pf' => 'previously passing test(s) now FAILING! :(',
1274 'fn' => 'previously FAILING test(s) removed O_o',
1275 'nf' => 'new FAILING test(s) :(',
1276 'ff' => 'still FAILING test(s) :(',
1279 $prevResults = array();
1281 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1282 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1283 foreach ( $res as $row ) {
1284 if ( !$this->parent->regex
1285 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1287 $prevResults[$row->ti_name] = $row->ti_success;
1291 $combined = array_keys( $this->results + $prevResults );
1293 # Determine breakdown by change type
1294 $breakdown = array();
1295 foreach ( $combined as $test ) {
1296 if ( !isset( $prevResults[$test] ) ) {
1298 } elseif ( $prevResults[$test] == 1 ) {
1300 } else /* if ( $prevResults[$test] == 0 )*/ {
1303 if ( !isset( $this->results[$test] ) ) {
1305 } elseif ( $this->results[$test] == 1 ) {
1307 } else /*if ( $this->results[$test] == 0 ) */ {
1310 $code = $before . $after;
1311 if ( isset( $table[$code] ) ) {
1312 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1317 foreach ( $table as $code => $label ) {
1318 if( !empty( $breakdown[$code] ) ) {
1319 $count = count($breakdown[$code]);
1320 printf( "\n%4d %s\n", $count, $label );
1321 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1322 print " * $differing_test_name [$statusInfo]\n";
1327 print "No previous test runs to compare against.\n";
1334 ** Returns a string giving information about when a test last had a status change.
1335 ** Could help to track down when regressions were introduced, as distinct from tests
1336 ** which have never passed (which are more change requests than regressions).
1338 private function getTestStatusInfo($testname, $after) {
1340 // If we're looking at a test that has just been removed, then say when it first appeared.
1341 if ( $after == 'n' ) {
1342 $changedRun = $this->db->selectField ( 'testitem',
1344 array( 'ti_name' => $testname ),
1346 $appear = $this->db->selectRow ( 'testrun',
1347 array( 'tr_date', 'tr_mw_version' ),
1348 array( 'tr_id' => $changedRun ),
1350 return "First recorded appearance: "
1351 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1352 . ", " . $appear->tr_mw_version;
1355 // Otherwise, this test has previous recorded results.
1356 // See when this test last had a different result to what we're seeing now.
1358 'ti_name' => $testname,
1359 'ti_success' => ($after == 'f' ? "1" : "0") );
1360 if ( $this->curRun ) {
1361 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1364 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1366 // If no record of ever having had a different result.
1367 if ( is_null ( $changedRun ) ) {
1368 if ($after == "f") {
1369 return "Has never passed";
1371 return "Has never failed";
1375 // Otherwise, we're looking at a test whose status has changed.
1376 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1377 // In this situation, give as much info as we can as to when it changed status.
1378 $pre = $this->db->selectRow ( 'testrun',
1379 array( 'tr_date', 'tr_mw_version' ),
1380 array( 'tr_id' => $changedRun ),
1382 $post = $this->db->selectRow ( 'testrun',
1383 array( 'tr_date', 'tr_mw_version' ),
1384 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1386 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1390 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1394 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1395 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1401 * Commit transaction and clean up for result recording
1404 $this->lb->commitMasterChanges();
1405 $this->lb->closeAll();
1411 class DbTestRecorder extends DbTestPreviewer {
1413 * Set up result recording; insert a record for the run with the date
1414 * and all that fun stuff
1417 global $wgDBtype, $wgDBprefix, $options;
1420 if( ! $this->db->tableExists( 'testrun' )
1421 or ! $this->db->tableExists( 'testitem' ) )
1423 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1424 if ($wgDBtype === 'postgres')
1425 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1426 elseif ($wgDBtype === 'oracle')
1427 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1429 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1430 echo "OK, resuming.\n";
1435 $this->db->insert( 'testrun',
1437 'tr_date' => $this->db->timestamp(),
1438 'tr_mw_version' => isset( $options['setversion'] ) ?
1439 $options['setversion'] : SpecialVersion::getVersion(),
1440 'tr_php_version' => phpversion(),
1441 'tr_db_version' => $this->db->getServerVersion(),
1442 'tr_uname' => php_uname()
1445 if ($wgDBtype === 'postgres')
1446 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1448 $this->curRun = $this->db->insertId();
1452 * Record an individual test item's success or failure to the db
1453 * @param string $test
1454 * @param bool $result
1456 function record( $test, $result ) {
1457 parent::record( $test, $result );
1458 $this->db->insert( 'testitem',
1460 'ti_run' => $this->curRun,
1462 'ti_success' => $result ? 1 : 0,
1468 class RemoteTestRecorder extends TestRecorder {
1471 $this->results = array();
1472 $this->ping( 'running' );
1475 function record( $test, $result ) {
1476 parent::record( $test, $result );
1477 $this->results[$test] = (bool)$result;
1481 $this->ping( 'complete', $this->results );
1486 * Inform a CodeReview instance that we've started or completed a test run...
1487 * @param $remote array: info on remote target
1488 * @param $status string: "running" - tell it we've started
1489 * "complete" - provide test results array
1490 * "abort" - something went horribly awry
1491 * @param $data array of test name => true/false
1493 function ping( $status, $results=false ) {
1494 global $wgParserTestRemote, $IP;
1496 $remote = $wgParserTestRemote;
1497 $revId = SpecialVersion::getSvnRevision( $IP );
1498 $jsonResults = json_encode( $results );
1501 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1505 // Generate a hash MAC to validate our credentials
1512 if( $status == "complete" ) {
1513 $message[] = $jsonResults;
1515 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1518 'action' => 'codetestupload',
1520 'repo' => $remote['repo'],
1521 'suite' => $remote['suite'],
1523 'status' => $status,
1526 if( $status == "complete" ) {
1527 $postData['results'] = $jsonResults;
1529 $response = $this->post( $remote['api-url'], $postData );
1531 if( $response === false ) {
1532 print "CodeReview info upload failed to reach server.\n";
1535 $responseData = json_decode( $response, true );
1536 if( !is_array( $responseData ) ) {
1537 print "CodeReview API response not recognized...\n";
1538 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1541 if( isset( $responseData['error'] ) ) {
1542 $code = $responseData['error']['code'];
1543 $info = $responseData['error']['info'];
1544 print "CodeReview info upload failed: $code $info\n";
1549 function post( $url, $data ) {
1550 return Http::post( $url, array( 'postData' => $data) );
1554 class TestFileIterator implements Iterator {
1563 function __construct( $file, $parser = null ) {
1566 $this->file = $file;
1567 $this->fh = fopen($this->file, "rt");
1569 wfDie( "Couldn't open file '$file'\n" );
1572 $this->parser = $parser;
1574 if( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1575 $this->lineNum = $this->index = 0;
1578 function setParser( ParserTest $parser ) {
1579 $this->parser = $parser;
1583 if(fseek($this->fh, 0)) {
1584 wfDie( "Couldn't fseek to the start of '$filename'\n" );
1589 $this->readNextTest();
1594 function current() {
1599 return $this->index;
1603 if($this->readNextTest()) {
1612 return $this->eof != true;
1615 function readNextTest() {
1619 while( false !== ($line = fgets( $this->fh ) ) ) {
1622 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1623 $section = strtolower( $matches[1] );
1624 if( $section == 'endarticle') {
1625 if( !isset( $data['text'] ) ) {
1626 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
1628 if( !isset( $data['article'] ) ) {
1629 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
1631 if( $this->parser ) $this->parser->addArticle($this->parser->chomp($data['article']), $this->parser->chomp($data['text']),
1637 if( $section == 'endhooks' ) {
1638 if( !isset( $data['hooks'] ) ) {
1639 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
1641 foreach( explode( "\n", $data['hooks'] ) as $line ) {
1642 $line = trim( $line );
1644 if( $this->parser ) $this->parser->requireHook( $line );
1651 if( $section == 'endfunctionhooks' ) {
1652 if( !isset( $data['functionhooks'] ) ) {
1653 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
1655 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
1656 $line = trim( $line );
1658 if( $this->parser ) $this->parser->requireFunctionHook( $line );
1665 if( $section == 'end' ) {
1666 if( !isset( $data['test'] ) ) {
1667 wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
1669 if( !isset( $data['input'] ) ) {
1670 wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
1672 if( !isset( $data['result'] ) ) {
1673 wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
1675 if( !isset( $data['options'] ) ) {
1676 $data['options'] = '';
1678 if (!isset( $data['config'] ) )
1679 $data['config'] = '';
1681 if ( $this->parser && (preg_match('/\\bdisabled\\b/i', $data['options'])
1682 || !preg_match("/{$this->parser->regex}/i", $data['test'])) && !$this->parser->runDisabled ) {
1688 if ( $this->parser &&
1689 preg_match('/\\bmath\\b/i', $data['options']) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1690 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1696 if( $this->parser ) {
1697 $this->test = array(
1698 'test' => $this->parser->chomp( $data['test'] ),
1699 'input' => $this->parser->chomp( $data['input'] ),
1700 'result' => $this->parser->chomp( $data['result'] ),
1701 'options' => $this->parser->chomp( $data['options'] ),
1702 'config' => $this->parser->chomp( $data['config'] ) );
1704 $this->test['test'] = $data['test'];
1708 if ( isset ($data[$section] ) ) {
1709 wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
1711 $data[$section] = '';
1715 $data[$section] .= $line;