2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @ingroup Maintenance
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record'. 'run-disabled' );
29 $optionsWithArgs = array( 'regex', 'seed', 'setversion' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
37 * @ingroup Maintenance
41 * boolean $color whereas output should be colorized
46 * boolean $showOutput Show test output
51 * boolean $useTemporaryTables Use temporary tables for the temporary database
53 private $useTemporaryTables = true;
56 * boolean $databaseSetupDone True if the database has been set up
58 private $databaseSetupDone = false;
61 * string $oldTablePrefix Original table prefix
63 private $oldTablePrefix;
65 private $maxFuzzTestLength = 300;
66 private $fuzzSeed = 0;
67 private $memoryLimit = 50;
70 * Sets terminal colorization and diff/quick modes depending on OS and
71 * command-line options (--color and --quick).
73 public function ParserTest() {
76 # Only colorize output if stdout is a terminal.
77 $this->color = !wfIsWindows() && posix_isatty(1);
79 if( isset( $options['color'] ) ) {
80 switch( $options['color'] ) {
90 $this->term = $this->color
91 ? new AnsiTermColorer()
92 : new DummyTermColorer();
94 $this->showDiffs = !isset( $options['quick'] );
95 $this->showProgress = !isset( $options['quiet'] );
96 $this->showFailure = !(
97 isset( $options['quiet'] )
98 && ( isset( $options['record'] )
99 || isset( $options['compare'] ) ) ); // redundant output
101 $this->showOutput = isset( $options['show-output'] );
104 if (isset($options['regex'])) {
105 if ( isset( $options['record'] ) ) {
106 echo "Warning: --record cannot be used with --regex, disabling --record\n";
107 unset( $options['record'] );
109 $this->regex = $options['regex'];
115 if( isset( $options['record'] ) ) {
116 $this->recorder = new DbTestRecorder( $this );
117 } elseif( isset( $options['compare'] ) ) {
118 $this->recorder = new DbTestPreviewer( $this );
120 $this->recorder = new TestRecorder( $this );
122 $this->keepUploads = isset( $options['keep-uploads'] );
124 if ( isset( $options['seed'] ) ) {
125 $this->fuzzSeed = intval( $options['seed'] ) - 1;
128 $this->runDisabled = isset( $options['run-disabled'] );
130 $this->hooks = array();
131 $this->functionHooks = array();
135 * Remove last character if it is a newline
137 private function chomp($s) {
138 if (substr($s, -1) === "\n") {
139 return substr($s, 0, -1);
147 * Run a fuzz test series
148 * Draw input from a set of test files
150 function fuzzTest( $filenames ) {
151 $dict = $this->getFuzzInput( $filenames );
152 $dictSize = strlen( $dict );
153 $logMaxLength = log( $this->maxFuzzTestLength );
154 $this->setupDatabase();
155 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
160 $opts = ParserOptions::newFromUser( $user );
161 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
164 // Generate test input
165 mt_srand( ++$this->fuzzSeed );
166 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
168 while ( strlen( $input ) < $totalLength ) {
169 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
170 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
171 $offset = mt_rand( 0, $dictSize - $hairLength );
172 $input .= substr( $dict, $offset, $hairLength );
175 $this->setupGlobals();
176 $parser = $this->getParser();
179 $parser->parse( $input, $title, $opts );
181 } catch ( Exception $exception ) {
186 echo "Test failed with seed {$this->fuzzSeed}\n";
195 $this->teardownGlobals();
196 $parser->__destruct();
198 if ( $numTotal % 100 == 0 ) {
199 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
200 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
202 echo "Out of memory:\n";
203 $memStats = $this->getMemoryBreakdown();
204 foreach ( $memStats as $name => $usage ) {
205 echo "$name: $usage\n";
214 * Get an input dictionary from a set of parser test files
216 function getFuzzInput( $filenames ) {
218 foreach( $filenames as $filename ) {
219 $contents = file_get_contents( $filename );
220 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
221 foreach ( $matches[1] as $match ) {
222 $dict .= $match . "\n";
229 * Get a memory usage breakdown
231 function getMemoryBreakdown() {
233 foreach ( $GLOBALS as $name => $value ) {
234 $memStats['$'.$name] = strlen( serialize( $value ) );
236 $classes = get_declared_classes();
237 foreach ( $classes as $class ) {
238 $rc = new ReflectionClass( $class );
239 $props = $rc->getStaticProperties();
240 $memStats[$class] = strlen( serialize( $props ) );
241 $methods = $rc->getMethods();
242 foreach ( $methods as $method ) {
243 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
246 $functions = get_defined_functions();
247 foreach ( $functions['user'] as $function ) {
248 $rf = new ReflectionFunction( $function );
249 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
260 * Run a series of tests listed in the given text files.
261 * Each test consists of a brief description, wikitext input,
262 * and the expected HTML output.
264 * Prints status updates on stdout and counts up the total
265 * number and percentage of passed tests.
267 * @param array of strings $filenames
268 * @return bool True if passed all tests, false if any tests failed.
270 public function runTestsFromFiles( $filenames ) {
271 $this->recorder->start();
272 $this->setupDatabase();
274 foreach( $filenames as $filename ) {
275 $ok = $this->runFile( $filename ) && $ok;
277 $this->teardownDatabase();
278 $this->recorder->report();
279 $this->recorder->end();
283 private function runFile( $filename ) {
284 $infile = fopen( $filename, 'rt' );
286 wfDie( "Couldn't open file '$filename'\n" );
289 $relative = wfRelativePath( $filename, $IP );
290 $this->showRunFile( $relative );
297 while( false !== ($line = fgets( $infile ) ) ) {
300 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
301 $section = strtolower( $matches[1] );
302 if( $section == 'endarticle') {
303 if( !isset( $data['text'] ) ) {
304 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
306 if( !isset( $data['article'] ) ) {
307 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
309 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
314 if( $section == 'endhooks' ) {
315 if( !isset( $data['hooks'] ) ) {
316 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
318 foreach( explode( "\n", $data['hooks'] ) as $line ) {
319 $line = trim( $line );
321 $this->requireHook( $line );
328 if( $section == 'endfunctionhooks' ) {
329 if( !isset( $data['functionhooks'] ) ) {
330 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
332 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
333 $line = trim( $line );
335 $this->requireFunctionHook( $line );
342 if( $section == 'end' ) {
343 if( !isset( $data['test'] ) ) {
344 wfDie( "'end' without 'test' at line $n of $filename\n" );
346 if( !isset( $data['input'] ) ) {
347 wfDie( "'end' without 'input' at line $n of $filename\n" );
349 if( !isset( $data['result'] ) ) {
350 wfDie( "'end' without 'result' at line $n of $filename\n" );
352 if( !isset( $data['options'] ) ) {
353 $data['options'] = '';
356 $data['options'] = $this->chomp( $data['options'] );
358 if (!isset( $data['config'] ) )
359 $data['config'] = '';
361 if ( (preg_match('/\\bdisabled\\b/i', $data['options'])
362 || !preg_match("/{$this->regex}/i", $data['test'])) && !$this->runDisabled ) {
368 $result = $this->runTest(
369 $this->chomp( $data['test'] ),
370 $this->chomp( $data['input'] ),
371 $this->chomp( $data['result'] ),
372 $this->chomp( $data['options'] ),
373 $this->chomp( $data['config'] )
375 $ok = $ok && $result;
376 $this->recorder->record( $this->chomp( $data['test'] ), $result );
381 if ( isset ($data[$section] ) ) {
382 wfDie( "duplicate section '$section' at line $n of $filename\n" );
384 $data[$section] = '';
388 $data[$section] .= $line;
391 if ( $this->showProgress ) {
398 * Get a Parser object
400 function getParser() {
401 global $wgParserConf;
402 $class = $wgParserConf['class'];
403 $parser = new $class( $wgParserConf );
404 foreach( $this->hooks as $tag => $callback ) {
405 $parser->setHook( $tag, $callback );
407 foreach( $this->functionHooks as $tag => $bits ) {
408 list( $callback, $flags ) = $bits;
409 $parser->setFunctionHook( $tag, $callback, $flags );
411 wfRunHooks( 'ParserTestParser', array( &$parser ) );
416 * Run a given wikitext input through a freshly-constructed wiki parser,
417 * and compare the output against the expected results.
418 * Prints status and explanatory messages to stdout.
420 * @param string $input Wikitext to try rendering
421 * @param string $result Result to output
424 private function runTest( $desc, $input, $result, $opts, $config ) {
425 if( $this->showProgress ) {
426 $this->showTesting( $desc );
429 $opts = $this->parseOptions( $opts );
430 $this->setupGlobals($opts, $config);
433 $options = ParserOptions::newFromUser( $user );
435 if ( isset( $opts['math'] ) ) {
436 # XXX this should probably be done by the ParserOptions
437 $options->setUseTex(true);
441 if (isset( $opts['title'] ) ) {
442 $titleText = $opts['title'];
445 $titleText = 'Parser test';
448 $noxml = isset( $opts['noxml'] );
449 $local = isset( $opts['local'] );
450 $parser = $this->getParser();
451 $title = Title::newFromText( $titleText );
454 if( isset( $opts['pst'] ) ) {
455 $out = $parser->preSaveTransform( $input, $title, $user, $options );
456 } elseif( isset( $opts['msg'] ) ) {
457 $out = $parser->transformMsg( $input, $options );
458 } elseif( isset( $opts['section'] ) ) {
459 $section = $opts['section'];
460 $out = $parser->getSection( $input, $section );
461 } elseif( isset( $opts['replace'] ) ) {
462 $section = $opts['replace'][0];
463 $replace = $opts['replace'][1];
464 $out = $parser->replaceSection( $input, $section, $replace );
465 } elseif( isset( $opts['comment'] ) ) {
466 $linker = $user->getSkin();
467 $out = $linker->formatComment( $input, $title, $local );
469 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
470 $out = $output->getText();
472 if (isset( $opts['ill'] ) ) {
473 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
474 } elseif( isset( $opts['cat'] ) ) {
476 $wgOut->addCategoryLinks($output->getCategories());
477 $cats = $wgOut->getCategoryLinks();
478 if ( isset( $cats['normal'] ) ) {
479 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
485 $result = $this->tidy($result);
488 $this->teardownGlobals();
490 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
491 return $this->showSuccess( $desc );
493 return $this->showFailure( $desc, $result, $out );
499 * Use a regex to find out the value of an option
500 * @param $key name of option val to retrieve
501 * @param $opts Options array to look in
502 * @param $defaults Default value returned if not found
504 private static function getOptionValue( $key, $opts, $default ) {
505 $key = strtolower( $key );
506 if( isset( $opts[$key] ) ) {
513 private function parseOptions( $instring ) {
515 $lines = explode( "\n", $instring );
520 // foo=bar,"baz quux"
544 \[\[[^]]*\]\] # Link target
552 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
553 foreach( $matches as $bits ) {
554 $match = array_shift( $bits );
555 $key = strtolower( array_shift( $bits ) );
556 if( count( $bits ) == 0 ) {
558 } elseif( count( $bits ) == 1 ) {
559 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
562 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
569 private function cleanupOption( $opt ) {
570 if( substr( $opt, 0, 1 ) == '"' ) {
571 return substr( $opt, 1, -1 );
573 if( substr( $opt, 0, 2 ) == '[[' ) {
574 return substr( $opt, 2, -2 );
580 * Set up the global variables for a consistent environment for each test.
581 * Ideally this should replace the global configuration entirely.
583 private function setupGlobals($opts = '', $config = '') {
584 if( !isset( $this->uploadDir ) ) {
585 $this->uploadDir = $this->setupUploadDir();
588 # Find out values for some special options.
590 self::getOptionValue( 'language', $opts, 'en' );
592 self::getOptionValue( 'variant', $opts, false );
594 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
595 $linkHolderBatchSize =
596 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
599 'wgServer' => 'http://localhost',
600 'wgScript' => '/index.php',
601 'wgScriptPath' => '/',
602 'wgArticlePath' => '/wiki/$1',
603 'wgActionPaths' => array(),
604 'wgLocalFileRepo' => array(
605 'class' => 'LocalRepo',
607 'directory' => $this->uploadDir,
608 'url' => 'http://example.com/images',
610 'transformVia404' => false,
612 'wgEnableUploads' => true,
613 'wgStyleSheetPath' => '/skins',
614 'wgSitename' => 'MediaWiki',
615 'wgServerName' => 'Britney Spears',
616 'wgLanguageCode' => $lang,
617 'wgContLanguageCode' => $lang,
618 'wgDBprefix' => 'parsertest_',
619 'wgRawHtml' => isset( $opts['rawhtml'] ),
621 'wgContLang' => null,
622 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
623 'wgMaxTocLevel' => $maxtoclevel,
624 'wgCapitalLinks' => true,
625 'wgNoFollowLinks' => true,
626 'wgNoFollowDomainExceptions' => array(),
627 'wgThumbnailScriptPath' => false,
629 'wgLocaltimezone' => 'UTC',
630 'wgAllowExternalImages' => true,
631 'wgUseTidy' => false,
632 'wgDefaultLanguageVariant' => $variant,
633 'wgVariantArticlePath' => false,
634 'wgGroupPermissions' => array( '*' => array(
635 'createaccount' => true,
638 'createpage' => true,
639 'createtalk' => true,
641 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
642 'wgDefaultExternalStore' => array(),
643 'wgForeignFileRepos' => array(),
644 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
645 'wgEnforceHtmlIds' => true,
646 'wgExternalLinkTarget' => false,
647 'wgAlwaysUseTidy' => false,
651 $configLines = explode( "\n", $config );
653 foreach( $configLines as $line ) {
654 list( $var, $value ) = explode( '=', $line, 2 );
656 $settings[$var] = eval("return $value;" );
660 $this->savedGlobals = array();
661 foreach( $settings as $var => $val ) {
662 $this->savedGlobals[$var] = $GLOBALS[$var];
663 $GLOBALS[$var] = $val;
665 $langObj = Language::factory( $lang );
666 $GLOBALS['wgLang'] = $langObj;
667 $GLOBALS['wgContLang'] = $langObj;
668 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
670 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
673 $wgUser = new User();
677 * List of temporary tables to create, without prefix.
678 * Some of these probably aren't necessary.
680 private function listTables() {
682 $tables = array('user', 'page', 'page_restrictions',
683 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
684 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
685 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
686 'recentchanges', 'watchlist', 'math', 'interwiki',
687 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
688 'archive', 'user_groups', 'page_props', 'category'
691 if ($wgDBtype === 'mysql')
692 array_push( $tables, 'searchindex' );
694 // Allow extensions to add to the list of tables to duplicate;
695 // may be necessary if they hook into page save or other code
696 // which will require them while running tests.
697 wfRunHooks( 'ParserTestTables', array( &$tables ) );
703 * Set up a temporary set of wiki tables to work with for the tests.
704 * Currently this will only be done once per run, and any changes to
705 * the db will be visible to later tests in the run.
707 private function setupDatabase() {
708 global $wgDBprefix, $wgDBtype;
709 if ( $this->databaseSetupDone ) {
712 if ( $wgDBprefix === 'parsertest_' ) {
713 throw new MWException( 'setupDatabase should be called before setupGlobals' );
715 $this->databaseSetupDone = true;
716 $this->oldTablePrefix = $wgDBprefix;
718 # CREATE TEMPORARY TABLE breaks if there is more than one server
719 # FIXME: r40209 makes temporary tables break even with just one server
720 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
721 if ( true || wfGetLB()->getServerCount() != 1 ) {
722 $this->useTemporaryTables = false;
725 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
727 $db = wfGetDB( DB_MASTER );
728 $tables = $this->listTables();
730 if ( !( $wgDBtype == 'mysql' && strcmp( $db->getServerVersion(), '4.1' ) < 0 ) ) {
731 # Database that supports CREATE TABLE ... LIKE
733 if( $wgDBtype == 'postgres' ) {
734 $def = 'INCLUDING DEFAULTS';
735 $temporary = 'TEMPORARY';
739 foreach ( $tables as $tbl ) {
740 # Clean up from previous aborted run. So that table escaping
741 # works correctly across DB engines, we need to change the pre-
742 # fix back and forth so tableName() works right.
743 $this->changePrefix( $this->oldTablePrefix );
744 $oldTableName = $db->tableName( $tbl );
745 $this->changePrefix( 'parsertest_' );
746 $newTableName = $db->tableName( $tbl );
748 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' ) {
749 $db->query( "DROP TABLE $newTableName" );
752 $db->query( "CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)" );
755 # Hack for MySQL versions < 4.1, which don't support
756 # "CREATE TABLE ... LIKE". Note that
757 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
758 # would not create the indexes we need....
760 # Note that we don't bother changing around the prefixes here be-
761 # cause we know we're using MySQL anyway.
762 foreach ($tables as $tbl) {
763 $oldTableName = $db->tableName( $tbl );
764 $res = $db->query("SHOW CREATE TABLE $oldTableName");
765 $row = $db->fetchRow($res);
767 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
768 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
769 if ($create === $create_tmp) {
770 # Couldn't do replacement
771 wfDie("could not create temporary table $tbl");
773 $db->query($create_tmp);
777 $this->changePrefix( 'parsertest_' );
779 # Hack: insert a few Wikipedia in-project interwiki prefixes,
780 # for testing inter-language links
781 $db->insert( 'interwiki', array(
782 array( 'iw_prefix' => 'wikipedia',
783 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
785 array( 'iw_prefix' => 'meatball',
786 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
788 array( 'iw_prefix' => 'zh',
789 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
791 array( 'iw_prefix' => 'es',
792 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
794 array( 'iw_prefix' => 'fr',
795 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
797 array( 'iw_prefix' => 'ru',
798 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
802 # Hack: Insert an image to work with
803 $db->insert( 'image', array(
804 'img_name' => 'Foobar.jpg',
806 'img_description' => 'Some lame file',
808 'img_user_text' => 'WikiSysop',
809 'img_timestamp' => $db->timestamp( '20010115123500' ),
813 'img_media_type' => MEDIATYPE_BITMAP,
814 'img_major_mime' => "image",
815 'img_minor_mime' => "jpeg",
816 'img_metadata' => serialize( array() ),
819 # Update certain things in site_stats
820 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
822 # Reinitialise the LocalisationCache to match the database state
823 Language::getLocalisationCache()->unloadAll();
827 * Change the table prefix on all open DB connections/
829 protected function changePrefix( $prefix ) {
831 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
832 $wgDBprefix = $prefix;
835 public function changeLBPrefix( $lb, $prefix ) {
836 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
839 public function changeDBPrefix( $db, $prefix ) {
840 $db->tablePrefix( $prefix );
843 private function teardownDatabase() {
845 if ( !$this->databaseSetupDone ) {
848 $this->changePrefix( $this->oldTablePrefix );
849 $this->databaseSetupDone = false;
850 if ( $this->useTemporaryTables ) {
851 # Don't need to do anything
856 $tables = $this->listTables();
857 $db = wfGetDB( DB_MASTER );
858 foreach ( $tables as $table ) {
859 $db->query( "DROP TABLE `parsertest_$table`" );
864 * Create a dummy uploads directory which will contain a couple
865 * of files in order to pass existence tests.
866 * @return string The directory
868 private function setupUploadDir() {
870 if ( $this->keepUploads ) {
871 $dir = wfTempDir() . '/mwParser-images';
872 if ( is_dir( $dir ) ) {
876 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
879 wfDebug( "Creating upload directory $dir\n" );
880 if ( file_exists( $dir ) ) {
881 wfDebug( "Already exists!\n" );
884 wfMkdirParents( $dir . '/3/3a' );
885 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
890 * Restore default values and perform any necessary clean-up
891 * after each test runs.
893 private function teardownGlobals() {
894 RepoGroup::destroySingleton();
895 FileCache::destroySingleton();
896 LinkCache::singleton()->clear();
897 foreach( $this->savedGlobals as $var => $val ) {
898 $GLOBALS[$var] = $val;
900 if( isset( $this->uploadDir ) ) {
901 $this->teardownUploadDir( $this->uploadDir );
902 unset( $this->uploadDir );
907 * Remove the dummy uploads directory
909 private function teardownUploadDir( $dir ) {
910 if ( $this->keepUploads ) {
914 // delete the files first, then the dirs.
917 "$dir/3/3a/Foobar.jpg",
918 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
919 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
920 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
921 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
931 "$dir/thumb/3/3a/Foobar.jpg",
941 * Delete the specified files, if they exist.
942 * @param array $files full paths to files to delete.
944 private static function deleteFiles( $files ) {
945 foreach( $files as $file ) {
946 if( file_exists( $file ) ) {
953 * Delete the specified directories, if they exist. Must be empty.
954 * @param array $dirs full paths to directories to delete.
956 private static function deleteDirs( $dirs ) {
957 foreach( $dirs as $dir ) {
958 if( is_dir( $dir ) ) {
965 * "Running test $desc..."
967 protected function showTesting( $desc ) {
968 print "Running test $desc... ";
972 * Print a happy success message.
974 * @param string $desc The test name
977 protected function showSuccess( $desc ) {
978 if( $this->showProgress ) {
979 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
985 * Print a failure message and provide some explanatory output
986 * about what went wrong if so configured.
988 * @param string $desc The test name
989 * @param string $result Expected HTML output
990 * @param string $html Actual HTML output
993 protected function showFailure( $desc, $result, $html ) {
994 if( $this->showFailure ) {
995 if( !$this->showProgress ) {
996 # In quiet mode we didn't show the 'Testing' message before the
997 # test, in case it succeeded. Show it now:
998 $this->showTesting( $desc );
1000 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1001 if ( $this->showOutput ) {
1002 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1004 if( $this->showDiffs ) {
1005 print $this->quickDiff( $result, $html );
1006 if( !$this->wellFormed( $html ) ) {
1007 print "XML error: $this->mXmlError\n";
1015 * Run given strings through a diff and return the (colorized) output.
1016 * Requires writable /tmp directory and a 'diff' command in the PATH.
1018 * @param string $input
1019 * @param string $output
1020 * @param string $inFileTail Tailing for the input file name
1021 * @param string $outFileTail Tailing for the output file name
1024 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
1025 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1027 $infile = "$prefix-$inFileTail";
1028 $this->dumpToFile( $input, $infile );
1030 $outfile = "$prefix-$outFileTail";
1031 $this->dumpToFile( $output, $outfile );
1033 $diff = `diff -au $infile $outfile`;
1037 return $this->colorDiff( $diff );
1041 * Write the given string to a file, adding a final newline.
1043 * @param string $data
1044 * @param string $filename
1046 private function dumpToFile( $data, $filename ) {
1047 $file = fopen( $filename, "wt" );
1048 fwrite( $file, $data . "\n" );
1053 * Colorize unified diff output if set for ANSI color output.
1054 * Subtractions are colored blue, additions red.
1056 * @param string $text
1059 protected function colorDiff( $text ) {
1060 return preg_replace(
1061 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1062 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1063 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1068 * Show "Reading tests from ..."
1070 * @param String $path
1072 protected function showRunFile( $path ){
1073 print $this->term->color( 1 ) .
1074 "Reading tests from \"$path\"..." .
1075 $this->term->reset() .
1080 * Insert a temporary test article
1081 * @param string $name the title, including any prefix
1082 * @param string $text the article text
1083 * @param int $line the input line number, for reporting errors
1085 private function addArticle($name, $text, $line) {
1086 $this->setupGlobals();
1087 $title = Title::newFromText( $name );
1088 if ( is_null($title) ) {
1089 wfDie( "invalid title at line $line\n" );
1092 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1094 wfDie( "duplicate article at line $line\n" );
1097 $art = new Article($title);
1098 $art->insertNewArticle($text, '', false, false );
1099 $this->teardownGlobals();
1103 * Steal a callback function from the primary parser, save it for
1104 * application to our scary parser. If the hook is not installed,
1105 * die a painful dead to warn the others.
1106 * @param string $name
1108 private function requireHook( $name ) {
1110 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1111 if( isset( $wgParser->mTagHooks[$name] ) ) {
1112 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1114 wfDie( "This test suite requires the '$name' hook extension.\n" );
1119 * Steal a callback function from the primary parser, save it for
1120 * application to our scary parser. If the hook is not installed,
1121 * die a painful dead to warn the others.
1122 * @param string $name
1124 private function requireFunctionHook( $name ) {
1126 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1127 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1128 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1130 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1135 * Run the "tidy" command on text if the $wgUseTidy
1138 * @param string $text the text to tidy
1142 private function tidy( $text ) {
1145 $text = Parser::tidy($text);
1150 private function wellFormed( $text ) {
1152 Sanitizer::hackDocType() .
1157 $parser = xml_parser_create( "UTF-8" );
1159 # case folding violates XML standard, turn it off
1160 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1162 if( !xml_parse( $parser, $html, true ) ) {
1163 $err = xml_error_string( xml_get_error_code( $parser ) );
1164 $position = xml_get_current_byte_index( $parser );
1165 $fragment = $this->extractFragment( $html, $position );
1166 $this->mXmlError = "$err at byte $position:\n$fragment";
1167 xml_parser_free( $parser );
1170 xml_parser_free( $parser );
1174 private function extractFragment( $text, $position ) {
1175 $start = max( 0, $position - 10 );
1176 $before = $position - $start;
1178 $this->term->color( 34 ) .
1179 substr( $text, $start, $before ) .
1180 $this->term->color( 0 ) .
1181 $this->term->color( 31 ) .
1182 $this->term->color( 1 ) .
1183 substr( $text, $position, 1 ) .
1184 $this->term->color( 0 ) .
1185 $this->term->color( 34 ) .
1186 substr( $text, $position + 1, 9 ) .
1187 $this->term->color( 0 ) .
1189 $display = str_replace( "\n", ' ', $fragment );
1191 str_repeat( ' ', $before ) .
1192 $this->term->color( 31 ) .
1194 $this->term->color( 0 );
1195 return "$display\n$caret";
1199 class AnsiTermColorer {
1200 function __construct() {
1204 * Return ANSI terminal escape code for changing text attribs/color
1206 * @param string $color Semicolon-separated list of attribute/color codes
1209 public function color( $color ) {
1210 global $wgCommandLineDarkBg;
1211 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1212 return "\x1b[{$light}{$color}m";
1216 * Return ANSI terminal escape code for restoring default text attributes
1220 public function reset() {
1221 return $this->color( 0 );
1225 /* A colour-less terminal */
1226 class DummyTermColorer {
1227 public function color( $color ) {
1231 public function reset() {
1236 class TestRecorder {
1240 function __construct( $parent ) {
1241 $this->parent = $parent;
1242 $this->term = $parent->term;
1250 function record( $test, $result ) {
1252 $this->success += ($result ? 1 : 0);
1260 if( $this->total > 0 ) {
1261 $this->reportPercentage( $this->success, $this->total );
1263 wfDie( "No tests found.\n" );
1267 function reportPercentage( $success, $total ) {
1268 $ratio = wfPercent( 100 * $success / $total );
1269 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1270 if( $success == $total ) {
1271 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1273 $failed = $total - $success ;
1274 print $this->term->color( 31 ) . "$failed tests failed!";
1276 print $this->term->reset() . "\n";
1277 return ($success == $total);
1281 class DbTestPreviewer extends TestRecorder {
1282 protected $lb; ///< Database load balancer
1283 protected $db; ///< Database connection to the main DB
1284 protected $curRun; ///< run ID number for the current run
1285 protected $prevRun; ///< run ID number for the previous run, if any
1286 protected $results; ///< Result array
1289 * This should be called before the table prefix is changed
1291 function __construct( $parent ) {
1292 parent::__construct( $parent );
1293 $this->lb = wfGetLBFactory()->newMainLB();
1294 // This connection will have the wiki's table prefix, not parsertest_
1295 $this->db = $this->lb->getConnection( DB_MASTER );
1299 * Set up result recording; insert a record for the run with the date
1300 * and all that fun stuff
1303 global $wgDBtype, $wgDBprefix;
1306 if( ! $this->db->tableExists( 'testrun' )
1307 or ! $this->db->tableExists( 'testitem' ) )
1309 print "WARNING> `testrun` table not found in database.\n";
1310 $this->prevRun = false;
1312 // We'll make comparisons against the previous run later...
1313 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1315 $this->results = array();
1318 function record( $test, $result ) {
1319 parent::record( $test, $result );
1320 $this->results[$test] = $result;
1324 if( $this->prevRun ) {
1325 // f = fail, p = pass, n = nonexistent
1326 // codes show before then after
1328 'fp' => 'previously failing test(s) now PASSING! :)',
1329 'pn' => 'previously PASSING test(s) removed o_O',
1330 'np' => 'new PASSING test(s) :)',
1332 'pf' => 'previously passing test(s) now FAILING! :(',
1333 'fn' => 'previously FAILING test(s) removed O_o',
1334 'nf' => 'new FAILING test(s) :(',
1335 'ff' => 'still FAILING test(s) :(',
1338 $prevResults = array();
1340 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1341 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1342 foreach ( $res as $row ) {
1343 if ( !$this->parent->regex
1344 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1346 $prevResults[$row->ti_name] = $row->ti_success;
1350 $combined = array_keys( $this->results + $prevResults );
1352 # Determine breakdown by change type
1353 $breakdown = array();
1354 foreach ( $combined as $test ) {
1355 if ( !isset( $prevResults[$test] ) ) {
1357 } elseif ( $prevResults[$test] == 1 ) {
1359 } else /* if ( $prevResults[$test] == 0 )*/ {
1362 if ( !isset( $this->results[$test] ) ) {
1364 } elseif ( $this->results[$test] == 1 ) {
1366 } else /*if ( $this->results[$test] == 0 ) */ {
1369 $code = $before . $after;
1370 if ( isset( $table[$code] ) ) {
1371 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1376 foreach ( $table as $code => $label ) {
1377 if( !empty( $breakdown[$code] ) ) {
1378 $count = count($breakdown[$code]);
1379 printf( "\n%4d %s\n", $count, $label );
1380 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1381 print " * $differing_test_name [$statusInfo]\n";
1386 print "No previous test runs to compare against.\n";
1393 ** Returns a string giving information about when a test last had a status change.
1394 ** Could help to track down when regressions were introduced, as distinct from tests
1395 ** which have never passed (which are more change requests than regressions).
1397 private function getTestStatusInfo($testname, $after) {
1399 // If we're looking at a test that has just been removed, then say when it first appeared.
1400 if ( $after == 'n' ) {
1401 $changedRun = $this->db->selectField ( 'testitem',
1403 array( 'ti_name' => $testname ),
1405 $appear = $this->db->selectRow ( 'testrun',
1406 array( 'tr_date', 'tr_mw_version' ),
1407 array( 'tr_id' => $changedRun ),
1409 return "First recorded appearance: "
1410 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1411 . ", " . $appear->tr_mw_version;
1414 // Otherwise, this test has previous recorded results.
1415 // See when this test last had a different result to what we're seeing now.
1417 'ti_name' => $testname,
1418 'ti_success' => ($after == 'f' ? "1" : "0") );
1419 if ( $this->curRun ) {
1420 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1423 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1425 // If no record of ever having had a different result.
1426 if ( is_null ( $changedRun ) ) {
1427 if ($after == "f") {
1428 return "Has never passed";
1430 return "Has never failed";
1434 // Otherwise, we're looking at a test whose status has changed.
1435 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1436 // In this situation, give as much info as we can as to when it changed status.
1437 $pre = $this->db->selectRow ( 'testrun',
1438 array( 'tr_date', 'tr_mw_version' ),
1439 array( 'tr_id' => $changedRun ),
1441 $post = $this->db->selectRow ( 'testrun',
1442 array( 'tr_date', 'tr_mw_version' ),
1443 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1445 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1449 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1453 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1454 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1460 * Commit transaction and clean up for result recording
1463 $this->lb->commitMasterChanges();
1464 $this->lb->closeAll();
1470 class DbTestRecorder extends DbTestPreviewer {
1472 * Set up result recording; insert a record for the run with the date
1473 * and all that fun stuff
1476 global $wgDBtype, $wgDBprefix, $options;
1479 if( ! $this->db->tableExists( 'testrun' )
1480 or ! $this->db->tableExists( 'testitem' ) )
1482 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1483 if ($wgDBtype === 'postgres')
1484 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1486 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1487 echo "OK, resuming.\n";
1492 $this->db->insert( 'testrun',
1494 'tr_date' => $this->db->timestamp(),
1495 'tr_mw_version' => isset( $options['setversion'] ) ?
1496 $options['setversion'] : SpecialVersion::getVersion(),
1497 'tr_php_version' => phpversion(),
1498 'tr_db_version' => $this->db->getServerVersion(),
1499 'tr_uname' => php_uname()
1502 if ($wgDBtype === 'postgres')
1503 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1505 $this->curRun = $this->db->insertId();
1509 * Record an individual test item's success or failure to the db
1510 * @param string $test
1511 * @param bool $result
1513 function record( $test, $result ) {
1514 parent::record( $test, $result );
1515 $this->db->insert( 'testitem',
1517 'ti_run' => $this->curRun,
1519 'ti_success' => $result ? 1 : 0,