2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @ingroup Maintenance
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record', 'run-disabled' );
29 $optionsWithArgs = array( 'regex', 'seed', 'setversion' );
31 if ( !defined( "NO_COMMAND_LINE" ) ) {
32 require_once( dirname( __FILE__ ) . '/commandLine.inc' );
34 require_once( "$IP/maintenance/parserTestsParserHook.php" );
35 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
36 require_once( "$IP/maintenance/parserTestsParserTime.php" );
39 * @ingroup Maintenance
43 * boolean $color whereas output should be colorized
48 * boolean $showOutput Show test output
53 * boolean $useTemporaryTables Use temporary tables for the temporary database
55 private $useTemporaryTables = true;
58 * boolean $databaseSetupDone True if the database has been set up
60 private $databaseSetupDone = false;
63 * string $oldTablePrefix Original table prefix
65 private $oldTablePrefix;
67 private $maxFuzzTestLength = 300;
68 private $fuzzSeed = 0;
69 private $memoryLimit = 50;
72 * Sets terminal colorization and diff/quick modes depending on OS and
73 * command-line options (--color and --quick).
75 public function ParserTest() {
78 # Only colorize output if stdout is a terminal.
79 $this->color = !wfIsWindows() && posix_isatty( 1 );
81 if ( isset( $options['color'] ) ) {
82 switch( $options['color'] ) {
92 $this->term = $this->color
93 ? new AnsiTermColorer()
94 : new DummyTermColorer();
96 $this->showDiffs = !isset( $options['quick'] );
97 $this->showProgress = !isset( $options['quiet'] );
98 $this->showFailure = !(
99 isset( $options['quiet'] )
100 && ( isset( $options['record'] )
101 || isset( $options['compare'] ) ) ); // redundant output
103 $this->showOutput = isset( $options['show-output'] );
106 if ( isset( $options['regex'] ) ) {
107 if ( isset( $options['record'] ) ) {
108 echo "Warning: --record cannot be used with --regex, disabling --record\n";
109 unset( $options['record'] );
111 $this->regex = $options['regex'];
117 if ( isset( $options['record'] ) ) {
118 $this->recorder = new DbTestRecorder( $this );
119 } elseif ( isset( $options['compare'] ) ) {
120 $this->recorder = new DbTestPreviewer( $this );
121 } elseif ( isset( $options['upload'] ) ) {
122 $this->recorder = new RemoteTestRecorder( $this );
123 } elseif ( class_exists( 'PHPUnitTestRecorder' ) ) {
124 $this->recorder = new PHPUnitTestRecorder( $this );
126 $this->recorder = new TestRecorder( $this );
128 $this->keepUploads = isset( $options['keep-uploads'] );
130 if ( isset( $options['seed'] ) ) {
131 $this->fuzzSeed = intval( $options['seed'] ) - 1;
134 $this->runDisabled = isset( $options['run-disabled'] );
136 $this->hooks = array();
137 $this->functionHooks = array();
141 * Remove last character if it is a newline
143 public function chomp( $s ) {
144 if ( substr( $s, -1 ) === "\n" ) {
145 return substr( $s, 0, -1 );
153 * Run a fuzz test series
154 * Draw input from a set of test files
156 function fuzzTest( $filenames ) {
157 $dict = $this->getFuzzInput( $filenames );
158 $dictSize = strlen( $dict );
159 $logMaxLength = log( $this->maxFuzzTestLength );
160 $this->setupDatabase();
161 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
166 $opts = ParserOptions::newFromUser( $user );
167 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
170 // Generate test input
171 mt_srand( ++$this->fuzzSeed );
172 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
174 while ( strlen( $input ) < $totalLength ) {
175 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
176 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
177 $offset = mt_rand( 0, $dictSize - $hairLength );
178 $input .= substr( $dict, $offset, $hairLength );
181 $this->setupGlobals();
182 $parser = $this->getParser();
185 $parser->parse( $input, $title, $opts );
187 } catch ( Exception $exception ) {
192 echo "Test failed with seed {$this->fuzzSeed}\n";
201 $this->teardownGlobals();
202 $parser->__destruct();
204 if ( $numTotal % 100 == 0 ) {
205 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
206 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
208 echo "Out of memory:\n";
209 $memStats = $this->getMemoryBreakdown();
210 foreach ( $memStats as $name => $usage ) {
211 echo "$name: $usage\n";
220 * Get an input dictionary from a set of parser test files
222 function getFuzzInput( $filenames ) {
224 foreach ( $filenames as $filename ) {
225 $contents = file_get_contents( $filename );
226 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
227 foreach ( $matches[1] as $match ) {
228 $dict .= $match . "\n";
235 * Get a memory usage breakdown
237 function getMemoryBreakdown() {
239 foreach ( $GLOBALS as $name => $value ) {
240 $memStats['$' . $name] = strlen( serialize( $value ) );
242 $classes = get_declared_classes();
243 foreach ( $classes as $class ) {
244 $rc = new ReflectionClass( $class );
245 $props = $rc->getStaticProperties();
246 $memStats[$class] = strlen( serialize( $props ) );
247 $methods = $rc->getMethods();
248 foreach ( $methods as $method ) {
249 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
252 $functions = get_defined_functions();
253 foreach ( $functions['user'] as $function ) {
254 $rf = new ReflectionFunction( $function );
255 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
266 * Run a series of tests listed in the given text files.
267 * Each test consists of a brief description, wikitext input,
268 * and the expected HTML output.
270 * Prints status updates on stdout and counts up the total
271 * number and percentage of passed tests.
273 * @param $filenames Array of strings
274 * @return Boolean: true if passed all tests, false if any tests failed.
276 public function runTestsFromFiles( $filenames ) {
277 $this->recorder->start();
278 $this->setupDatabase();
280 foreach ( $filenames as $filename ) {
281 $tests = new TestFileIterator( $filename, $this );
282 $ok = $this->runTests( $tests ) && $ok;
284 $this->teardownDatabase();
285 $this->recorder->report();
286 $this->recorder->end();
290 function runTests( $tests ) {
292 foreach ( $tests as $i => $t ) {
294 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
295 $ok = $ok && $result;
296 $this->recorder->record( $t['test'], $result );
298 if ( $this->showProgress ) {
305 * Get a Parser object
307 function getParser( $preprocessor = null ) {
308 global $wgParserConf;
309 $class = $wgParserConf['class'];
310 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
311 foreach ( $this->hooks as $tag => $callback ) {
312 $parser->setHook( $tag, $callback );
314 foreach ( $this->functionHooks as $tag => $bits ) {
315 list( $callback, $flags ) = $bits;
316 $parser->setFunctionHook( $tag, $callback, $flags );
318 wfRunHooks( 'ParserTestParser', array( &$parser ) );
323 * Run a given wikitext input through a freshly-constructed wiki parser,
324 * and compare the output against the expected results.
325 * Prints status and explanatory messages to stdout.
327 * @param $desc String: test's description
328 * @param $input String: wikitext to try rendering
329 * @param $result String: result to output
330 * @param $opts Array: test's options
331 * @param $config String: overrides for global variables, one per line
334 public function runTest( $desc, $input, $result, $opts, $config ) {
335 if ( $this->showProgress ) {
336 $this->showTesting( $desc );
339 $opts = $this->parseOptions( $opts );
340 $this->setupGlobals( $opts, $config );
343 $options = ParserOptions::newFromUser( $user );
346 if ( isset( $opts['title'] ) ) {
347 $titleText = $opts['title'];
350 $titleText = 'Parser test';
353 $noxml = isset( $opts['noxml'] );
354 $local = isset( $opts['local'] );
355 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
356 $parser = $this->getParser( $preprocessor );
357 $title = Title::newFromText( $titleText );
360 if ( isset( $opts['pst'] ) ) {
361 $out = $parser->preSaveTransform( $input, $title, $user, $options );
362 } elseif ( isset( $opts['msg'] ) ) {
363 $out = $parser->transformMsg( $input, $options );
364 } elseif ( isset( $opts['section'] ) ) {
365 $section = $opts['section'];
366 $out = $parser->getSection( $input, $section );
367 } elseif ( isset( $opts['replace'] ) ) {
368 $section = $opts['replace'][0];
369 $replace = $opts['replace'][1];
370 $out = $parser->replaceSection( $input, $section, $replace );
371 } elseif ( isset( $opts['comment'] ) ) {
372 $linker = $user->getSkin();
373 $out = $linker->formatComment( $input, $title, $local );
374 } elseif ( isset( $opts['preload'] ) ) {
375 $out = $parser->getpreloadText( $input, $title, $options );
377 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
378 $out = $output->getText();
380 if ( isset( $opts['showtitle'] ) ) {
381 if ( $output->getTitleText() ) $title = $output->getTitleText();
382 $out = "$title\n$out";
384 if ( isset( $opts['ill'] ) ) {
385 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
386 } elseif ( isset( $opts['cat'] ) ) {
388 $wgOut->addCategoryLinks( $output->getCategories() );
389 $cats = $wgOut->getCategoryLinks();
390 if ( isset( $cats['normal'] ) ) {
391 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
397 $result = $this->tidy( $result );
401 $this->teardownGlobals();
403 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
404 return $this->showSuccess( $desc );
406 return $this->showFailure( $desc, $result, $out );
412 * Use a regex to find out the value of an option
413 * @param $key String: name of option val to retrieve
414 * @param $opts Options array to look in
415 * @param $default Mixed: default value returned if not found
417 private static function getOptionValue( $key, $opts, $default ) {
418 $key = strtolower( $key );
419 if ( isset( $opts[$key] ) ) {
426 private function parseOptions( $instring ) {
428 $lines = explode( "\n", $instring );
433 // foo=bar,"baz quux"
457 \[\[[^]]*\]\] # Link target
465 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
466 foreach ( $matches as $bits ) {
467 $match = array_shift( $bits );
468 $key = strtolower( array_shift( $bits ) );
469 if ( count( $bits ) == 0 ) {
471 } elseif ( count( $bits ) == 1 ) {
472 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
475 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
482 private function cleanupOption( $opt ) {
483 if ( substr( $opt, 0, 1 ) == '"' ) {
484 return substr( $opt, 1, -1 );
486 if ( substr( $opt, 0, 2 ) == '[[' ) {
487 return substr( $opt, 2, -2 );
493 * Set up the global variables for a consistent environment for each test.
494 * Ideally this should replace the global configuration entirely.
496 private function setupGlobals( $opts = '', $config = '' ) {
498 if ( !isset( $this->uploadDir ) ) {
499 $this->uploadDir = $this->setupUploadDir();
502 # Find out values for some special options.
504 self::getOptionValue( 'language', $opts, 'en' );
506 self::getOptionValue( 'variant', $opts, false );
508 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
509 $linkHolderBatchSize =
510 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
513 'wgServer' => 'http://localhost',
514 'wgScript' => '/index.php',
515 'wgScriptPath' => '/',
516 'wgArticlePath' => '/wiki/$1',
517 'wgActionPaths' => array(),
518 'wgLocalFileRepo' => array(
519 'class' => 'LocalRepo',
521 'directory' => $this->uploadDir,
522 'url' => 'http://example.com/images',
524 'transformVia404' => false,
526 'wgEnableUploads' => true,
527 'wgStyleSheetPath' => '/skins',
528 'wgSitename' => 'MediaWiki',
529 'wgServerName' => 'Britney-Spears',
530 'wgLanguageCode' => $lang,
531 'wgContLanguageCode' => $lang,
532 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
533 'wgRawHtml' => isset( $opts['rawhtml'] ),
535 'wgContLang' => null,
536 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
537 'wgMaxTocLevel' => $maxtoclevel,
538 'wgCapitalLinks' => true,
539 'wgNoFollowLinks' => true,
540 'wgNoFollowDomainExceptions' => array(),
541 'wgThumbnailScriptPath' => false,
542 'wgUseImageResize' => false,
543 'wgUseTeX' => isset( $opts['math'] ),
544 'wgMathDirectory' => $this->uploadDir . '/math',
545 'wgLocaltimezone' => 'UTC',
546 'wgAllowExternalImages' => true,
547 'wgUseTidy' => false,
548 'wgDefaultLanguageVariant' => $variant,
549 'wgVariantArticlePath' => false,
550 'wgGroupPermissions' => array( '*' => array(
551 'createaccount' => true,
554 'createpage' => true,
555 'createtalk' => true,
557 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
558 'wgDefaultExternalStore' => array(),
559 'wgForeignFileRepos' => array(),
560 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
561 'wgExperimentalHtmlIds' => false,
562 'wgExternalLinkTarget' => false,
563 'wgAlwaysUseTidy' => false,
565 'wgWellFormedXml' => true,
566 'wgAllowMicrodataAttributes' => true,
570 $configLines = explode( "\n", $config );
572 foreach ( $configLines as $line ) {
573 list( $var, $value ) = explode( '=', $line, 2 );
575 $settings[$var] = eval( "return $value;" );
579 $this->savedGlobals = array();
580 foreach ( $settings as $var => $val ) {
581 if ( array_key_exists( $var, $GLOBALS ) ) {
582 $this->savedGlobals[$var] = $GLOBALS[$var];
584 $GLOBALS[$var] = $val;
586 $langObj = Language::factory( $lang );
587 $GLOBALS['wgLang'] = $langObj;
588 $GLOBALS['wgContLang'] = $langObj;
589 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
590 $GLOBALS['wgOut'] = new OutputPage;
592 MagicWord::clearCache();
595 $wgUser = new User();
599 * List of temporary tables to create, without prefix.
600 * Some of these probably aren't necessary.
602 private function listTables() {
604 $tables = array( 'user', 'page', 'page_restrictions',
605 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
606 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
607 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
608 'recentchanges', 'watchlist', 'math', 'interwiki',
609 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
610 'archive', 'user_groups', 'page_props', 'category'
613 if ( $wgDBtype === 'mysql' )
614 array_push( $tables, 'searchindex' );
616 // Allow extensions to add to the list of tables to duplicate;
617 // may be necessary if they hook into page save or other code
618 // which will require them while running tests.
619 wfRunHooks( 'ParserTestTables', array( &$tables ) );
625 * Set up a temporary set of wiki tables to work with for the tests.
626 * Currently this will only be done once per run, and any changes to
627 * the db will be visible to later tests in the run.
629 function setupDatabase() {
630 global $wgDBprefix, $wgDBtype;
631 if ( $this->databaseSetupDone ) {
634 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
635 throw new MWException( 'setupDatabase should be called before setupGlobals' );
637 $this->databaseSetupDone = true;
638 $this->oldTablePrefix = $wgDBprefix;
640 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
641 # It seems to have been fixed since (r55079?).
642 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
644 # CREATE TEMPORARY TABLE breaks if there is more than one server
645 if ( wfGetLB()->getServerCount() != 1 ) {
646 $this->useTemporaryTables = false;
649 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
651 $db = wfGetDB( DB_MASTER );
652 $tables = $this->listTables();
654 foreach ( $tables as $tbl ) {
655 # Clean up from previous aborted run. So that table escaping
656 # works correctly across DB engines, we need to change the pre-
657 # fix back and forth so tableName() works right.
658 $this->changePrefix( $this->oldTablePrefix );
659 $oldTableName = $db->tableName( $tbl );
660 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
661 $newTableName = $db->tableName( $tbl );
663 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
664 $db->query( "DROP TABLE $newTableName" );
667 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
669 if ( $wgDBtype == 'oracle' )
670 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
672 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
674 # Hack: insert a few Wikipedia in-project interwiki prefixes,
675 # for testing inter-language links
676 $db->insert( 'interwiki', array(
677 array( 'iw_prefix' => 'wikipedia',
678 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
680 array( 'iw_prefix' => 'meatball',
681 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
683 array( 'iw_prefix' => 'zh',
684 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
686 array( 'iw_prefix' => 'es',
687 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
689 array( 'iw_prefix' => 'fr',
690 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
692 array( 'iw_prefix' => 'ru',
693 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
698 if ( $wgDBtype == 'oracle' ) {
699 # Insert 0 and 1 user_ids to prevent FK violations
702 $db->insert( 'user', array(
704 'user_name' => 'Anonymous' ) );
706 # Hack-on-Hack: Insert a test user to be able to insert an image
707 $db->insert( 'user', array(
709 'user_name' => 'Tester' ) );
712 # Hack: Insert an image to work with
713 $db->insert( 'image', array(
714 'img_name' => 'Foobar.jpg',
716 'img_description' => 'Some lame file',
718 'img_user_text' => 'WikiSysop',
719 'img_timestamp' => $db->timestamp( '20010115123500' ),
723 'img_media_type' => MEDIATYPE_BITMAP,
724 'img_major_mime' => "image",
725 'img_minor_mime' => "jpeg",
726 'img_metadata' => serialize( array() ),
729 # This image will be blacklisted in [[MediaWiki:Bad image list]]
730 $db->insert( 'image', array(
731 'img_name' => 'Bad.jpg',
733 'img_description' => 'zomgnotcensored',
735 'img_user_text' => 'WikiSysop',
736 'img_timestamp' => $db->timestamp( '20010115123500' ),
740 'img_media_type' => MEDIATYPE_BITMAP,
741 'img_major_mime' => "image",
742 'img_minor_mime' => "jpeg",
743 'img_metadata' => serialize( array() ),
746 # Update certain things in site_stats
747 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
749 # Reinitialise the LocalisationCache to match the database state
750 Language::getLocalisationCache()->unloadAll();
752 # Make a new message cache
753 global $wgMessageCache, $wgMemc;
754 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
758 * Change the table prefix on all open DB connections/
760 protected function changePrefix( $prefix ) {
762 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
763 $wgDBprefix = $prefix;
766 public function changeLBPrefix( $lb, $prefix ) {
767 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
770 public function changeDBPrefix( $db, $prefix ) {
771 $db->tablePrefix( $prefix );
774 private function teardownDatabase() {
776 if ( !$this->databaseSetupDone ) {
779 $this->changePrefix( $this->oldTablePrefix );
780 $this->databaseSetupDone = false;
781 if ( $this->useTemporaryTables ) {
782 # Don't need to do anything
787 $tables = $this->listTables();
788 $db = wfGetDB( DB_MASTER );
789 foreach ( $tables as $table ) {
790 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
793 if ($wgDBtype == 'oracle')
794 $db->query('BEGIN FILL_WIKI_INFO; END;');
799 * Create a dummy uploads directory which will contain a couple
800 * of files in order to pass existence tests.
802 * @return String: the directory
804 private function setupUploadDir() {
806 if ( $this->keepUploads ) {
807 $dir = wfTempDir() . '/mwParser-images';
808 if ( is_dir( $dir ) ) {
812 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
815 wfDebug( "Creating upload directory $dir\n" );
816 if ( file_exists( $dir ) ) {
817 wfDebug( "Already exists!\n" );
820 wfMkdirParents( $dir . '/3/3a' );
821 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
823 wfMkdirParents( $dir . '/0/09' );
824 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
829 * Restore default values and perform any necessary clean-up
830 * after each test runs.
832 private function teardownGlobals() {
833 RepoGroup::destroySingleton();
834 LinkCache::singleton()->clear();
835 foreach ( $this->savedGlobals as $var => $val ) {
836 $GLOBALS[$var] = $val;
838 if ( isset( $this->uploadDir ) ) {
839 $this->teardownUploadDir( $this->uploadDir );
840 unset( $this->uploadDir );
845 * Remove the dummy uploads directory
847 private function teardownUploadDir( $dir ) {
848 if ( $this->keepUploads ) {
852 // delete the files first, then the dirs.
855 "$dir/3/3a/Foobar.jpg",
856 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
857 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
858 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
859 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
863 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
873 "$dir/thumb/3/3a/Foobar.jpg",
890 * Delete the specified files, if they exist.
891 * @param $files Array: full paths to files to delete.
893 private static function deleteFiles( $files ) {
894 foreach ( $files as $file ) {
895 if ( file_exists( $file ) ) {
902 * Delete the specified directories, if they exist. Must be empty.
903 * @param $dirs Array: full paths to directories to delete.
905 private static function deleteDirs( $dirs ) {
906 foreach ( $dirs as $dir ) {
907 if ( is_dir( $dir ) ) {
914 * "Running test $desc..."
916 protected function showTesting( $desc ) {
917 print "Running test $desc... ";
921 * Print a happy success message.
923 * @param $desc String: the test name
926 protected function showSuccess( $desc ) {
927 if ( $this->showProgress ) {
928 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
934 * Print a failure message and provide some explanatory output
935 * about what went wrong if so configured.
937 * @param $desc String: the test name
938 * @param $result String: expected HTML output
939 * @param $html String: actual HTML output
942 protected function showFailure( $desc, $result, $html ) {
943 if ( $this->showFailure ) {
944 if ( !$this->showProgress ) {
945 # In quiet mode we didn't show the 'Testing' message before the
946 # test, in case it succeeded. Show it now:
947 $this->showTesting( $desc );
949 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
950 if ( $this->showOutput ) {
951 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
953 if ( $this->showDiffs ) {
954 print $this->quickDiff( $result, $html );
955 if ( !$this->wellFormed( $html ) ) {
956 print "XML error: $this->mXmlError\n";
964 * Run given strings through a diff and return the (colorized) output.
965 * Requires writable /tmp directory and a 'diff' command in the PATH.
967 * @param $input String
968 * @param $output String
969 * @param $inFileTail String: tailing for the input file name
970 * @param $outFileTail String: tailing for the output file name
973 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
974 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
976 $infile = "$prefix-$inFileTail";
977 $this->dumpToFile( $input, $infile );
979 $outfile = "$prefix-$outFileTail";
980 $this->dumpToFile( $output, $outfile );
982 $diff = `diff -au $infile $outfile`;
986 return $this->colorDiff( $diff );
990 * Write the given string to a file, adding a final newline.
992 * @param $data String
993 * @param $filename String
995 private function dumpToFile( $data, $filename ) {
996 $file = fopen( $filename, "wt" );
997 fwrite( $file, $data . "\n" );
1002 * Colorize unified diff output if set for ANSI color output.
1003 * Subtractions are colored blue, additions red.
1005 * @param $text String
1008 protected function colorDiff( $text ) {
1009 return preg_replace(
1010 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1011 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1012 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1017 * Show "Reading tests from ..."
1019 * @param $path String
1021 public function showRunFile( $path ) {
1022 print $this->term->color( 1 ) .
1023 "Reading tests from \"$path\"..." .
1024 $this->term->reset() .
1029 * Insert a temporary test article
1030 * @param $name String: the title, including any prefix
1031 * @param $text String: the article text
1032 * @param $line Integer: the input line number, for reporting errors
1034 public function addArticle( $name, $text, $line ) {
1035 $this->setupGlobals();
1036 $title = Title::newFromText( $name );
1037 if ( is_null( $title ) ) {
1038 wfDie( "invalid title at line $line\n" );
1041 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1043 wfDie( "duplicate article '$name' at line $line\n" );
1046 $art = new Article( $title );
1047 $art->insertNewArticle( $text, '', false, false );
1049 $this->teardownGlobals();
1053 * Steal a callback function from the primary parser, save it for
1054 * application to our scary parser. If the hook is not installed,
1055 * die a painful dead to warn the others.
1057 * @param $name String
1059 public function requireHook( $name ) {
1061 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1062 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1063 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1065 wfDie( "This test suite requires the '$name' hook extension.\n" );
1070 * Steal a callback function from the primary parser, save it for
1071 * application to our scary parser. If the hook is not installed,
1072 * die a painful dead to warn the others.
1074 * @param $name String
1076 public function requireFunctionHook( $name ) {
1078 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1079 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1080 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1082 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1087 * Run the "tidy" command on text if the $wgUseTidy
1090 * @param $text String: the text to tidy
1094 private function tidy( $text ) {
1097 $text = Parser::tidy( $text );
1102 private function wellFormed( $text ) {
1104 Sanitizer::hackDocType() .
1109 $parser = xml_parser_create( "UTF-8" );
1111 # case folding violates XML standard, turn it off
1112 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1114 if ( !xml_parse( $parser, $html, true ) ) {
1115 $err = xml_error_string( xml_get_error_code( $parser ) );
1116 $position = xml_get_current_byte_index( $parser );
1117 $fragment = $this->extractFragment( $html, $position );
1118 $this->mXmlError = "$err at byte $position:\n$fragment";
1119 xml_parser_free( $parser );
1122 xml_parser_free( $parser );
1126 private function extractFragment( $text, $position ) {
1127 $start = max( 0, $position - 10 );
1128 $before = $position - $start;
1130 $this->term->color( 34 ) .
1131 substr( $text, $start, $before ) .
1132 $this->term->color( 0 ) .
1133 $this->term->color( 31 ) .
1134 $this->term->color( 1 ) .
1135 substr( $text, $position, 1 ) .
1136 $this->term->color( 0 ) .
1137 $this->term->color( 34 ) .
1138 substr( $text, $position + 1, 9 ) .
1139 $this->term->color( 0 ) .
1141 $display = str_replace( "\n", ' ', $fragment );
1143 str_repeat( ' ', $before ) .
1144 $this->term->color( 31 ) .
1146 $this->term->color( 0 );
1147 return "$display\n$caret";
1151 class AnsiTermColorer {
1152 function __construct() {
1156 * Return ANSI terminal escape code for changing text attribs/color
1158 * @param $color String: semicolon-separated list of attribute/color codes
1161 public function color( $color ) {
1162 global $wgCommandLineDarkBg;
1163 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1164 return "\x1b[{$light}{$color}m";
1168 * Return ANSI terminal escape code for restoring default text attributes
1172 public function reset() {
1173 return $this->color( 0 );
1177 /* A colour-less terminal */
1178 class DummyTermColorer {
1179 public function color( $color ) {
1183 public function reset() {
1188 class TestRecorder {
1192 function __construct( $parent ) {
1193 $this->parent = $parent;
1194 $this->term = $parent->term;
1202 function record( $test, $result ) {
1204 $this->success += ( $result ? 1 : 0 );
1212 if ( $this->total > 0 ) {
1213 $this->reportPercentage( $this->success, $this->total );
1215 wfDie( "No tests found.\n" );
1219 function reportPercentage( $success, $total ) {
1220 $ratio = wfPercent( 100 * $success / $total );
1221 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1222 if ( $success == $total ) {
1223 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1225 $failed = $total - $success ;
1226 print $this->term->color( 31 ) . "$failed tests failed!";
1228 print $this->term->reset() . "\n";
1229 return ( $success == $total );
1233 class DbTestPreviewer extends TestRecorder {
1234 protected $lb; // /< Database load balancer
1235 protected $db; // /< Database connection to the main DB
1236 protected $curRun; // /< run ID number for the current run
1237 protected $prevRun; // /< run ID number for the previous run, if any
1238 protected $results; // /< Result array
1241 * This should be called before the table prefix is changed
1243 function __construct( $parent ) {
1244 parent::__construct( $parent );
1245 $this->lb = wfGetLBFactory()->newMainLB();
1246 // This connection will have the wiki's table prefix, not parsertest_
1247 $this->db = $this->lb->getConnection( DB_MASTER );
1251 * Set up result recording; insert a record for the run with the date
1252 * and all that fun stuff
1258 if ( ! $this->db->tableExists( 'testrun' )
1259 or ! $this->db->tableExists( 'testitem' ) )
1261 print "WARNING> `testrun` table not found in database.\n";
1262 $this->prevRun = false;
1264 // We'll make comparisons against the previous run later...
1265 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1267 $this->results = array();
1270 function record( $test, $result ) {
1271 parent::record( $test, $result );
1272 $this->results[$test] = $result;
1276 if ( $this->prevRun ) {
1277 // f = fail, p = pass, n = nonexistent
1278 // codes show before then after
1280 'fp' => 'previously failing test(s) now PASSING! :)',
1281 'pn' => 'previously PASSING test(s) removed o_O',
1282 'np' => 'new PASSING test(s) :)',
1284 'pf' => 'previously passing test(s) now FAILING! :(',
1285 'fn' => 'previously FAILING test(s) removed O_o',
1286 'nf' => 'new FAILING test(s) :(',
1287 'ff' => 'still FAILING test(s) :(',
1290 $prevResults = array();
1292 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1293 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1294 foreach ( $res as $row ) {
1295 if ( !$this->parent->regex
1296 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1298 $prevResults[$row->ti_name] = $row->ti_success;
1302 $combined = array_keys( $this->results + $prevResults );
1304 # Determine breakdown by change type
1305 $breakdown = array();
1306 foreach ( $combined as $test ) {
1307 if ( !isset( $prevResults[$test] ) ) {
1309 } elseif ( $prevResults[$test] == 1 ) {
1311 } else /* if ( $prevResults[$test] == 0 )*/ {
1314 if ( !isset( $this->results[$test] ) ) {
1316 } elseif ( $this->results[$test] == 1 ) {
1318 } else /*if ( $this->results[$test] == 0 ) */ {
1321 $code = $before . $after;
1322 if ( isset( $table[$code] ) ) {
1323 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1328 foreach ( $table as $code => $label ) {
1329 if ( !empty( $breakdown[$code] ) ) {
1330 $count = count( $breakdown[$code] );
1331 printf( "\n%4d %s\n", $count, $label );
1332 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1333 print " * $differing_test_name [$statusInfo]\n";
1338 print "No previous test runs to compare against.\n";
1345 ** Returns a string giving information about when a test last had a status change.
1346 ** Could help to track down when regressions were introduced, as distinct from tests
1347 ** which have never passed (which are more change requests than regressions).
1349 private function getTestStatusInfo( $testname, $after ) {
1351 // If we're looking at a test that has just been removed, then say when it first appeared.
1352 if ( $after == 'n' ) {
1353 $changedRun = $this->db->selectField ( 'testitem',
1355 array( 'ti_name' => $testname ),
1357 $appear = $this->db->selectRow ( 'testrun',
1358 array( 'tr_date', 'tr_mw_version' ),
1359 array( 'tr_id' => $changedRun ),
1361 return "First recorded appearance: "
1362 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1363 . ", " . $appear->tr_mw_version;
1366 // Otherwise, this test has previous recorded results.
1367 // See when this test last had a different result to what we're seeing now.
1369 'ti_name' => $testname,
1370 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1371 if ( $this->curRun ) {
1372 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1375 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1377 // If no record of ever having had a different result.
1378 if ( is_null ( $changedRun ) ) {
1379 if ( $after == "f" ) {
1380 return "Has never passed";
1382 return "Has never failed";
1386 // Otherwise, we're looking at a test whose status has changed.
1387 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1388 // In this situation, give as much info as we can as to when it changed status.
1389 $pre = $this->db->selectRow ( 'testrun',
1390 array( 'tr_date', 'tr_mw_version' ),
1391 array( 'tr_id' => $changedRun ),
1393 $post = $this->db->selectRow ( 'testrun',
1394 array( 'tr_date', 'tr_mw_version' ),
1395 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1397 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1401 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1405 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1406 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1412 * Commit transaction and clean up for result recording
1415 $this->lb->commitMasterChanges();
1416 $this->lb->closeAll();
1422 class DbTestRecorder extends DbTestPreviewer {
1424 * Set up result recording; insert a record for the run with the date
1425 * and all that fun stuff
1428 global $wgDBtype, $options;
1431 if ( ! $this->db->tableExists( 'testrun' )
1432 or ! $this->db->tableExists( 'testitem' ) )
1434 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1435 if ( $wgDBtype === 'postgres' )
1436 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1437 elseif ( $wgDBtype === 'oracle' )
1438 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1440 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1441 echo "OK, resuming.\n";
1446 $this->db->insert( 'testrun',
1448 'tr_date' => $this->db->timestamp(),
1449 'tr_mw_version' => isset( $options['setversion'] ) ?
1450 $options['setversion'] : SpecialVersion::getVersion(),
1451 'tr_php_version' => phpversion(),
1452 'tr_db_version' => $this->db->getServerVersion(),
1453 'tr_uname' => php_uname()
1456 if ( $wgDBtype === 'postgres' )
1457 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1459 $this->curRun = $this->db->insertId();
1463 * Record an individual test item's success or failure to the db
1465 * @param $test String
1466 * @param $result Boolean
1468 function record( $test, $result ) {
1469 parent::record( $test, $result );
1470 $this->db->insert( 'testitem',
1472 'ti_run' => $this->curRun,
1474 'ti_success' => $result ? 1 : 0,
1480 class RemoteTestRecorder extends TestRecorder {
1483 $this->results = array();
1484 $this->ping( 'running' );
1487 function record( $test, $result ) {
1488 parent::record( $test, $result );
1489 $this->results[$test] = (bool)$result;
1493 $this->ping( 'complete', $this->results );
1498 * Inform a CodeReview instance that we've started or completed a test run...
1500 * @param $status string: "running" - tell it we've started
1501 * "complete" - provide test results array
1502 * "abort" - something went horribly awry
1503 * @param $results array of test name => true/false
1505 function ping( $status, $results = false ) {
1506 global $wgParserTestRemote, $IP;
1508 $remote = $wgParserTestRemote;
1509 $revId = SpecialVersion::getSvnRevision( $IP );
1510 $jsonResults = json_encode( $results );
1513 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1517 // Generate a hash MAC to validate our credentials
1524 if ( $status == "complete" ) {
1525 $message[] = $jsonResults;
1527 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1530 'action' => 'codetestupload',
1532 'repo' => $remote['repo'],
1533 'suite' => $remote['suite'],
1535 'status' => $status,
1538 if ( $status == "complete" ) {
1539 $postData['results'] = $jsonResults;
1541 $response = $this->post( $remote['api-url'], $postData );
1543 if ( $response === false ) {
1544 print "CodeReview info upload failed to reach server.\n";
1547 $responseData = FormatJson::decode( $response, true );
1548 if ( !is_array( $responseData ) ) {
1549 print "CodeReview API response not recognized...\n";
1550 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1553 if ( isset( $responseData['error'] ) ) {
1554 $code = $responseData['error']['code'];
1555 $info = $responseData['error']['info'];
1556 print "CodeReview info upload failed: $code $info\n";
1561 function post( $url, $data ) {
1562 return Http::post( $url, array( 'postData' => $data ) );
1566 class TestFileIterator implements Iterator {
1575 function __construct( $file, $parser = null ) {
1578 $this->file = $file;
1579 $this->fh = fopen( $this->file, "rt" );
1581 wfDie( "Couldn't open file '$file'\n" );
1584 $this->parser = $parser;
1586 if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1587 $this->lineNum = $this->index = 0;
1590 function setParser( ParserTest $parser ) {
1591 $this->parser = $parser;
1595 if ( fseek( $this->fh, 0 ) ) {
1596 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1606 function current() {
1611 return $this->index;
1615 if ( $this->readNextTest() ) {
1624 return $this->eof != true;
1627 function readNextTest() {
1631 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1634 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1635 $section = strtolower( $matches[1] );
1636 if ( $section == 'endarticle' ) {
1637 if ( !isset( $data['text'] ) ) {
1638 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1640 if ( !isset( $data['article'] ) ) {
1641 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1643 if ( $this->parser ) {
1644 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1651 if ( $section == 'endhooks' ) {
1652 if ( !isset( $data['hooks'] ) ) {
1653 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1655 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1656 $line = trim( $line );
1658 if ( $this->parser ) $this->parser->requireHook( $line );
1665 if ( $section == 'endfunctionhooks' ) {
1666 if ( !isset( $data['functionhooks'] ) ) {
1667 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1669 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1670 $line = trim( $line );
1672 if ( $this->parser ) $this->parser->requireFunctionHook( $line );
1679 if ( $section == 'end' ) {
1680 if ( !isset( $data['test'] ) ) {
1681 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1683 if ( !isset( $data['input'] ) ) {
1684 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1686 if ( !isset( $data['result'] ) ) {
1687 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1689 if ( !isset( $data['options'] ) ) {
1690 $data['options'] = '';
1692 if ( !isset( $data['config'] ) )
1693 $data['config'] = '';
1696 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1697 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
1703 if ( $this->parser &&
1704 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1705 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1711 if ( $this->parser ) {
1712 $this->test = array(
1713 'test' => $this->parser->chomp( $data['test'] ),
1714 'input' => $this->parser->chomp( $data['input'] ),
1715 'result' => $this->parser->chomp( $data['result'] ),
1716 'options' => $this->parser->chomp( $data['options'] ),
1717 'config' => $this->parser->chomp( $data['config'] ) );
1719 $this->test['test'] = $data['test'];
1723 if ( isset ( $data[$section] ) ) {
1724 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1726 $data[$section] = '';
1730 $data[$section] .= $line;