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' );
29 $optionsWithArgs = array( 'regex', 'seed' );
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->hooks = array();
129 $this->functionHooks = array();
133 * Remove last character if it is a newline
135 private function chomp($s) {
136 if (substr($s, -1) === "\n") {
137 return substr($s, 0, -1);
145 * Run a fuzz test series
146 * Draw input from a set of test files
148 function fuzzTest( $filenames ) {
149 $dict = $this->getFuzzInput( $filenames );
150 $dictSize = strlen( $dict );
151 $logMaxLength = log( $this->maxFuzzTestLength );
152 $this->setupDatabase();
153 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
158 $opts = ParserOptions::newFromUser( $user );
159 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
162 // Generate test input
163 mt_srand( ++$this->fuzzSeed );
164 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
166 while ( strlen( $input ) < $totalLength ) {
167 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
168 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
169 $offset = mt_rand( 0, $dictSize - $hairLength );
170 $input .= substr( $dict, $offset, $hairLength );
173 $this->setupGlobals();
174 $parser = $this->getParser();
177 $parser->parse( $input, $title, $opts );
179 } catch ( Exception $exception ) {
184 echo "Test failed with seed {$this->fuzzSeed}\n";
193 $this->teardownGlobals();
194 $parser->__destruct();
196 if ( $numTotal % 100 == 0 ) {
197 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
198 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
200 echo "Out of memory:\n";
201 $memStats = $this->getMemoryBreakdown();
202 foreach ( $memStats as $name => $usage ) {
203 echo "$name: $usage\n";
212 * Get an input dictionary from a set of parser test files
214 function getFuzzInput( $filenames ) {
216 foreach( $filenames as $filename ) {
217 $contents = file_get_contents( $filename );
218 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
219 foreach ( $matches[1] as $match ) {
220 $dict .= $match . "\n";
227 * Get a memory usage breakdown
229 function getMemoryBreakdown() {
231 foreach ( $GLOBALS as $name => $value ) {
232 $memStats['$'.$name] = strlen( serialize( $value ) );
234 $classes = get_declared_classes();
235 foreach ( $classes as $class ) {
236 $rc = new ReflectionClass( $class );
237 $props = $rc->getStaticProperties();
238 $memStats[$class] = strlen( serialize( $props ) );
239 $methods = $rc->getMethods();
240 foreach ( $methods as $method ) {
241 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
244 $functions = get_defined_functions();
245 foreach ( $functions['user'] as $function ) {
246 $rf = new ReflectionFunction( $function );
247 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
258 * Run a series of tests listed in the given text files.
259 * Each test consists of a brief description, wikitext input,
260 * and the expected HTML output.
262 * Prints status updates on stdout and counts up the total
263 * number and percentage of passed tests.
265 * @param array of strings $filenames
266 * @return bool True if passed all tests, false if any tests failed.
268 public function runTestsFromFiles( $filenames ) {
269 $this->recorder->start();
270 $this->setupDatabase();
272 foreach( $filenames as $filename ) {
273 $ok = $this->runFile( $filename ) && $ok;
275 $this->teardownDatabase();
276 $this->recorder->report();
277 $this->recorder->end();
281 private function runFile( $filename ) {
282 $infile = fopen( $filename, 'rt' );
284 wfDie( "Couldn't open $filename\n" );
287 $relative = wfRelativePath( $filename, $IP );
288 $this->showRunFile( $relative );
295 while( false !== ($line = fgets( $infile ) ) ) {
298 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
299 $section = strtolower( $matches[1] );
300 if( $section == 'endarticle') {
301 if( !isset( $data['text'] ) ) {
302 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
304 if( !isset( $data['article'] ) ) {
305 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
307 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
312 if( $section == 'endhooks' ) {
313 if( !isset( $data['hooks'] ) ) {
314 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
316 foreach( explode( "\n", $data['hooks'] ) as $line ) {
317 $line = trim( $line );
319 $this->requireHook( $line );
326 if( $section == 'endfunctionhooks' ) {
327 if( !isset( $data['functionhooks'] ) ) {
328 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
330 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
331 $line = trim( $line );
333 $this->requireFunctionHook( $line );
340 if( $section == 'end' ) {
341 if( !isset( $data['test'] ) ) {
342 wfDie( "'end' without 'test' at line $n of $filename\n" );
344 if( !isset( $data['input'] ) ) {
345 wfDie( "'end' without 'input' at line $n of $filename\n" );
347 if( !isset( $data['result'] ) ) {
348 wfDie( "'end' without 'result' at line $n of $filename\n" );
350 if( !isset( $data['options'] ) ) {
351 $data['options'] = '';
354 $data['options'] = $this->chomp( $data['options'] );
356 if (!isset( $data['config'] ) )
357 $data['config'] = '';
359 if (preg_match('/\\bdisabled\\b/i', $data['options'])
360 || !preg_match("/{$this->regex}/i", $data['test'])) {
366 $result = $this->runTest(
367 $this->chomp( $data['test'] ),
368 $this->chomp( $data['input'] ),
369 $this->chomp( $data['result'] ),
370 $this->chomp( $data['options'] ),
371 $this->chomp( $data['config'] )
373 $ok = $ok && $result;
374 $this->recorder->record( $this->chomp( $data['test'] ), $result );
379 if ( isset ($data[$section] ) ) {
380 wfDie( "duplicate section '$section' at line $n of $filename\n" );
382 $data[$section] = '';
386 $data[$section] .= $line;
389 if ( $this->showProgress ) {
396 * Get a Parser object
398 function getParser() {
399 global $wgParserConf;
400 $class = $wgParserConf['class'];
401 $parser = new $class( $wgParserConf );
402 foreach( $this->hooks as $tag => $callback ) {
403 $parser->setHook( $tag, $callback );
405 foreach( $this->functionHooks as $tag => $bits ) {
406 list( $callback, $flags ) = $bits;
407 $parser->setFunctionHook( $tag, $callback, $flags );
409 wfRunHooks( 'ParserTestParser', array( &$parser ) );
414 * Run a given wikitext input through a freshly-constructed wiki parser,
415 * and compare the output against the expected results.
416 * Prints status and explanatory messages to stdout.
418 * @param string $input Wikitext to try rendering
419 * @param string $result Result to output
422 private function runTest( $desc, $input, $result, $opts, $config ) {
423 if( $this->showProgress ) {
424 $this->showTesting( $desc );
427 $this->setupGlobals($opts, $config);
430 $options = ParserOptions::newFromUser( $user );
432 if (preg_match('/\\bmath\\b/i', $opts)) {
433 # XXX this should probably be done by the ParserOptions
434 $options->setUseTex(true);
438 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
442 $titleText = 'Parser test';
445 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
446 $parser = $this->getParser();
447 $title =& Title::makeTitle( NS_MAIN, $titleText );
450 if (preg_match('/\\bpst\\b/i', $opts)) {
451 $out = $parser->preSaveTransform( $input, $title, $user, $options );
452 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
453 $out = $parser->transformMsg( $input, $options );
454 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
455 $section = $matches[1];
456 $out = $parser->getSection( $input, $section );
457 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
458 $section = $matches[1];
459 $replace = $matches[2];
460 $out = $parser->replaceSection( $input, $section, $replace );
462 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
463 $out = $output->getText();
465 if (preg_match('/\\bill\\b/i', $opts)) {
466 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
467 } else if (preg_match('/\\bcat\\b/i', $opts)) {
469 $wgOut->addCategoryLinks($output->getCategories());
470 $cats = $wgOut->getCategoryLinks();
471 if ( isset( $cats['normal'] ) ) {
472 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
478 $result = $this->tidy($result);
481 $this->teardownGlobals();
483 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
484 return $this->showSuccess( $desc );
486 return $this->showFailure( $desc, $result, $out );
492 * Use a regex to find out the value of an option
493 * @param $regex A regex, the first group will be the value returned
494 * @param $opts Options line to look in
495 * @param $defaults Default value returned if the regex does not match
497 private static function getOptionValue( $regex, $opts, $default ) {
499 if( preg_match( $regex, $opts, $m ) ) {
507 * Set up the global variables for a consistent environment for each test.
508 * Ideally this should replace the global configuration entirely.
510 private function setupGlobals($opts = '', $config = '') {
511 if( !isset( $this->uploadDir ) ) {
512 $this->uploadDir = $this->setupUploadDir();
515 # Find out values for some special options.
517 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
519 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
521 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
522 $linkHolderBatchSize =
523 self::getOptionValue( '/wgLinkHolderBatchSize=(\d+)/', $opts, 1000 );
526 'wgServer' => 'http://localhost',
527 'wgScript' => '/index.php',
528 'wgScriptPath' => '/',
529 'wgArticlePath' => '/wiki/$1',
530 'wgActionPaths' => array(),
531 'wgLocalFileRepo' => array(
532 'class' => 'LocalRepo',
534 'directory' => $this->uploadDir,
535 'url' => 'http://example.com/images',
537 'transformVia404' => false,
539 'wgEnableUploads' => true,
540 'wgStyleSheetPath' => '/skins',
541 'wgSitename' => 'MediaWiki',
542 'wgServerName' => 'Britney Spears',
543 'wgLanguageCode' => $lang,
544 'wgContLanguageCode' => $lang,
545 'wgDBprefix' => 'parsertest_',
546 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
548 'wgContLang' => null,
549 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
550 'wgMaxTocLevel' => $maxtoclevel,
551 'wgCapitalLinks' => true,
552 'wgNoFollowLinks' => true,
553 'wgNoFollowDomainExceptions' => array(),
554 'wgThumbnailScriptPath' => false,
556 'wgLocaltimezone' => 'UTC',
557 'wgAllowExternalImages' => true,
558 'wgUseTidy' => false,
559 'wgDefaultLanguageVariant' => $variant,
560 'wgVariantArticlePath' => false,
561 'wgGroupPermissions' => array( '*' => array(
562 'createaccount' => true,
565 'createpage' => true,
566 'createtalk' => true,
568 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
569 'wgDefaultExternalStore' => array(),
570 'wgForeignFileRepos' => array(),
571 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
572 'wgEnforceHtmlIds' => true,
573 'wgExternalLinkTarget' => false,
574 'wgAlwaysUseTidy' => false,
578 $configLines = explode( "\n", $config );
580 foreach( $configLines as $line ) {
581 list( $var, $value ) = explode( '=', $line, 2 );
583 $settings[$var] = eval("return $value;" );
587 $this->savedGlobals = array();
588 foreach( $settings as $var => $val ) {
589 $this->savedGlobals[$var] = $GLOBALS[$var];
590 $GLOBALS[$var] = $val;
592 $langObj = Language::factory( $lang );
593 $GLOBALS['wgLang'] = $langObj;
594 $GLOBALS['wgContLang'] = $langObj;
595 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
597 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
600 $wgUser = new User();
604 * List of temporary tables to create, without prefix.
605 * Some of these probably aren't necessary.
607 private function listTables() {
609 $tables = array('user', 'page', 'page_restrictions',
610 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
611 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
612 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
613 'recentchanges', 'watchlist', 'math', 'interwiki',
614 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
615 'archive', 'user_groups', 'page_props', 'category'
618 if ($wgDBtype === 'mysql')
619 array_push( $tables, 'searchindex' );
621 // Allow extensions to add to the list of tables to duplicate;
622 // may be necessary if they hook into page save or other code
623 // which will require them while running tests.
624 wfRunHooks( 'ParserTestTables', array( &$tables ) );
630 * Set up a temporary set of wiki tables to work with for the tests.
631 * Currently this will only be done once per run, and any changes to
632 * the db will be visible to later tests in the run.
634 private function setupDatabase() {
635 global $wgDBprefix, $wgDBtype;
636 if ( $this->databaseSetupDone ) {
639 if ( $wgDBprefix === 'parsertest_' ) {
640 throw new MWException( 'setupDatabase should be called before setupGlobals' );
642 $this->databaseSetupDone = true;
643 $this->oldTablePrefix = $wgDBprefix;
645 # CREATE TEMPORARY TABLE breaks if there is more than one server
646 # FIXME: r40209 makes temporary tables break even with just one server
647 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
648 if ( true || wfGetLB()->getServerCount() != 1 ) {
649 $this->useTemporaryTables = false;
652 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
654 $db = wfGetDB( DB_MASTER );
655 $tables = $this->listTables();
657 if ( !( $wgDBtype == 'mysql' && strcmp( $db->getServerVersion(), '4.1' ) < 0 ) ) {
658 # Database that supports CREATE TABLE ... LIKE
660 if( $wgDBtype == 'postgres' ) {
661 $def = 'INCLUDING DEFAULTS';
662 $temporary = 'TEMPORARY';
666 foreach ( $tables as $tbl ) {
667 # Clean up from previous aborted run. So that table escaping
668 # works correctly across DB engines, we need to change the pre-
669 # fix back and forth so tableName() works right.
670 $this->changePrefix( $this->oldTablePrefix );
671 $oldTableName = $db->tableName( $tbl );
672 $this->changePrefix( 'parsertest_' );
673 $newTableName = $db->tableName( $tbl );
675 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' ) {
676 $db->query( "DROP TABLE $newTableName" );
679 $db->query( "CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)" );
682 # Hack for MySQL versions < 4.1, which don't support
683 # "CREATE TABLE ... LIKE". Note that
684 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
685 # would not create the indexes we need....
687 # Note that we don't bother changing around the prefixes here be-
688 # cause we know we're using MySQL anyway.
689 foreach ($tables as $tbl) {
690 $oldTableName = $db->tableName( $tbl );
691 $res = $db->query("SHOW CREATE TABLE $oldTableName");
692 $row = $db->fetchRow($res);
694 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
695 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
696 if ($create === $create_tmp) {
697 # Couldn't do replacement
698 wfDie("could not create temporary table $tbl");
700 $db->query($create_tmp);
704 $this->changePrefix( 'parsertest_' );
706 # Hack: insert a few Wikipedia in-project interwiki prefixes,
707 # for testing inter-language links
708 $db->insert( 'interwiki', array(
709 array( 'iw_prefix' => 'wikipedia',
710 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
712 array( 'iw_prefix' => 'meatball',
713 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
715 array( 'iw_prefix' => 'zh',
716 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
718 array( 'iw_prefix' => 'es',
719 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
721 array( 'iw_prefix' => 'fr',
722 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
724 array( 'iw_prefix' => 'ru',
725 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
729 # Hack: Insert an image to work with
730 $db->insert( 'image', array(
731 'img_name' => 'Foobar.jpg',
733 'img_description' => 'Some lame file',
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' => 1, 'ss_good_articles' => 1 ) );
751 * Change the table prefix on all open DB connections/
753 protected function changePrefix( $prefix ) {
755 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
756 $wgDBprefix = $prefix;
759 public function changeLBPrefix( $lb, $prefix ) {
760 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
763 public function changeDBPrefix( $db, $prefix ) {
764 $db->tablePrefix( $prefix );
767 private function teardownDatabase() {
769 if ( !$this->databaseSetupDone ) {
772 $this->changePrefix( $this->oldTablePrefix );
773 $this->databaseSetupDone = false;
774 if ( $this->useTemporaryTables ) {
775 # Don't need to do anything
780 $tables = $this->listTables();
781 $db = wfGetDB( DB_MASTER );
782 foreach ( $tables as $table ) {
783 $db->query( "DROP TABLE `parsertest_$table`" );
788 * Create a dummy uploads directory which will contain a couple
789 * of files in order to pass existence tests.
790 * @return string The directory
792 private function setupUploadDir() {
794 if ( $this->keepUploads ) {
795 $dir = wfTempDir() . '/mwParser-images';
796 if ( is_dir( $dir ) ) {
800 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
803 wfDebug( "Creating upload directory $dir\n" );
804 if ( file_exists( $dir ) ) {
805 wfDebug( "Already exists!\n" );
808 wfMkdirParents( $dir . '/3/3a' );
809 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
814 * Restore default values and perform any necessary clean-up
815 * after each test runs.
817 private function teardownGlobals() {
818 RepoGroup::destroySingleton();
819 FileCache::destroySingleton();
820 LinkCache::singleton()->clear();
821 foreach( $this->savedGlobals as $var => $val ) {
822 $GLOBALS[$var] = $val;
824 if( isset( $this->uploadDir ) ) {
825 $this->teardownUploadDir( $this->uploadDir );
826 unset( $this->uploadDir );
831 * Remove the dummy uploads directory
833 private function teardownUploadDir( $dir ) {
834 if ( $this->keepUploads ) {
838 // delete the files first, then the dirs.
841 "$dir/3/3a/Foobar.jpg",
842 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
843 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
844 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
845 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
855 "$dir/thumb/3/3a/Foobar.jpg",
865 * Delete the specified files, if they exist.
866 * @param array $files full paths to files to delete.
868 private static function deleteFiles( $files ) {
869 foreach( $files as $file ) {
870 if( file_exists( $file ) ) {
877 * Delete the specified directories, if they exist. Must be empty.
878 * @param array $dirs full paths to directories to delete.
880 private static function deleteDirs( $dirs ) {
881 foreach( $dirs as $dir ) {
882 if( is_dir( $dir ) ) {
889 * "Running test $desc..."
891 protected function showTesting( $desc ) {
892 print "Running test $desc... ";
896 * Print a happy success message.
898 * @param string $desc The test name
901 protected function showSuccess( $desc ) {
902 if( $this->showProgress ) {
903 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
909 * Print a failure message and provide some explanatory output
910 * about what went wrong if so configured.
912 * @param string $desc The test name
913 * @param string $result Expected HTML output
914 * @param string $html Actual HTML output
917 protected function showFailure( $desc, $result, $html ) {
918 if( $this->showFailure ) {
919 if( !$this->showProgress ) {
920 # In quiet mode we didn't show the 'Testing' message before the
921 # test, in case it succeeded. Show it now:
922 $this->showTesting( $desc );
924 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
925 if ( $this->showOutput ) {
926 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
928 if( $this->showDiffs ) {
929 print $this->quickDiff( $result, $html );
930 if( !$this->wellFormed( $html ) ) {
931 print "XML error: $this->mXmlError\n";
939 * Run given strings through a diff and return the (colorized) output.
940 * Requires writable /tmp directory and a 'diff' command in the PATH.
942 * @param string $input
943 * @param string $output
944 * @param string $inFileTail Tailing for the input file name
945 * @param string $outFileTail Tailing for the output file name
948 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
949 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
951 $infile = "$prefix-$inFileTail";
952 $this->dumpToFile( $input, $infile );
954 $outfile = "$prefix-$outFileTail";
955 $this->dumpToFile( $output, $outfile );
957 $diff = `diff -au $infile $outfile`;
961 return $this->colorDiff( $diff );
965 * Write the given string to a file, adding a final newline.
967 * @param string $data
968 * @param string $filename
970 private function dumpToFile( $data, $filename ) {
971 $file = fopen( $filename, "wt" );
972 fwrite( $file, $data . "\n" );
977 * Colorize unified diff output if set for ANSI color output.
978 * Subtractions are colored blue, additions red.
980 * @param string $text
983 protected function colorDiff( $text ) {
985 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
986 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
987 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
992 * Show "Reading tests from ..."
994 * @param String $path
996 protected function showRunFile( $path ){
997 print $this->term->color( 1 ) .
998 "Reading tests from \"$path\"..." .
999 $this->term->reset() .
1004 * Insert a temporary test article
1005 * @param string $name the title, including any prefix
1006 * @param string $text the article text
1007 * @param int $line the input line number, for reporting errors
1009 private function addArticle($name, $text, $line) {
1010 $this->setupGlobals();
1011 $title = Title::newFromText( $name );
1012 if ( is_null($title) ) {
1013 wfDie( "invalid title at line $line\n" );
1016 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1018 wfDie( "duplicate article at line $line\n" );
1021 $art = new Article($title);
1022 $art->insertNewArticle($text, '', false, false );
1023 $this->teardownGlobals();
1027 * Steal a callback function from the primary parser, save it for
1028 * application to our scary parser. If the hook is not installed,
1029 * die a painful dead to warn the others.
1030 * @param string $name
1032 private function requireHook( $name ) {
1034 if( isset( $wgParser->mTagHooks[$name] ) ) {
1035 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1037 wfDie( "This test suite requires the '$name' hook extension.\n" );
1042 * Steal a callback function from the primary parser, save it for
1043 * application to our scary parser. If the hook is not installed,
1044 * die a painful dead to warn the others.
1045 * @param string $name
1047 private function requireFunctionHook( $name ) {
1049 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1050 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1052 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1057 * Run the "tidy" command on text if the $wgUseTidy
1060 * @param string $text the text to tidy
1064 private function tidy( $text ) {
1067 $text = Parser::tidy($text);
1072 private function wellFormed( $text ) {
1074 Sanitizer::hackDocType() .
1079 $parser = xml_parser_create( "UTF-8" );
1081 # case folding violates XML standard, turn it off
1082 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1084 if( !xml_parse( $parser, $html, true ) ) {
1085 $err = xml_error_string( xml_get_error_code( $parser ) );
1086 $position = xml_get_current_byte_index( $parser );
1087 $fragment = $this->extractFragment( $html, $position );
1088 $this->mXmlError = "$err at byte $position:\n$fragment";
1089 xml_parser_free( $parser );
1092 xml_parser_free( $parser );
1096 private function extractFragment( $text, $position ) {
1097 $start = max( 0, $position - 10 );
1098 $before = $position - $start;
1100 $this->term->color( 34 ) .
1101 substr( $text, $start, $before ) .
1102 $this->term->color( 0 ) .
1103 $this->term->color( 31 ) .
1104 $this->term->color( 1 ) .
1105 substr( $text, $position, 1 ) .
1106 $this->term->color( 0 ) .
1107 $this->term->color( 34 ) .
1108 substr( $text, $position + 1, 9 ) .
1109 $this->term->color( 0 ) .
1111 $display = str_replace( "\n", ' ', $fragment );
1113 str_repeat( ' ', $before ) .
1114 $this->term->color( 31 ) .
1116 $this->term->color( 0 );
1117 return "$display\n$caret";
1121 class AnsiTermColorer {
1122 function __construct() {
1126 * Return ANSI terminal escape code for changing text attribs/color
1128 * @param string $color Semicolon-separated list of attribute/color codes
1131 public function color( $color ) {
1132 global $wgCommandLineDarkBg;
1133 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1134 return "\x1b[{$light}{$color}m";
1138 * Return ANSI terminal escape code for restoring default text attributes
1142 public function reset() {
1143 return $this->color( 0 );
1147 /* A colour-less terminal */
1148 class DummyTermColorer {
1149 public function color( $color ) {
1153 public function reset() {
1158 class TestRecorder {
1162 function __construct( $parent ) {
1163 $this->parent = $parent;
1164 $this->term = $parent->term;
1172 function record( $test, $result ) {
1174 $this->success += ($result ? 1 : 0);
1182 if( $this->total > 0 ) {
1183 $this->reportPercentage( $this->success, $this->total );
1185 wfDie( "No tests found.\n" );
1189 function reportPercentage( $success, $total ) {
1190 $ratio = wfPercent( 100 * $success / $total );
1191 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1192 if( $success == $total ) {
1193 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1195 $failed = $total - $success ;
1196 print $this->term->color( 31 ) . "$failed tests failed!";
1198 print $this->term->reset() . "\n";
1199 return ($success == $total);
1203 class DbTestPreviewer extends TestRecorder {
1204 protected $lb; ///< Database load balancer
1205 protected $db; ///< Database connection to the main DB
1206 protected $curRun; ///< run ID number for the current run
1207 protected $prevRun; ///< run ID number for the previous run, if any
1208 protected $results; ///< Result array
1211 * This should be called before the table prefix is changed
1213 function __construct( $parent ) {
1214 parent::__construct( $parent );
1215 $this->lb = wfGetLBFactory()->newMainLB();
1216 // This connection will have the wiki's table prefix, not parsertest_
1217 $this->db = $this->lb->getConnection( DB_MASTER );
1221 * Set up result recording; insert a record for the run with the date
1222 * and all that fun stuff
1225 global $wgDBtype, $wgDBprefix;
1228 if( ! $this->db->tableExists( 'testrun' )
1229 or ! $this->db->tableExists( 'testitem' ) )
1231 print "WARNING> `testrun` table not found in database.\n";
1232 $this->prevRun = false;
1234 // We'll make comparisons against the previous run later...
1235 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1237 $this->results = array();
1240 function record( $test, $result ) {
1241 parent::record( $test, $result );
1242 $this->results[$test] = $result;
1246 if( $this->prevRun ) {
1247 // f = fail, p = pass, n = nonexistent
1248 // codes show before then after
1250 'fp' => 'previously failing test(s) now PASSING! :)',
1251 'pn' => 'previously PASSING test(s) removed o_O',
1252 'np' => 'new PASSING test(s) :)',
1254 'pf' => 'previously passing test(s) now FAILING! :(',
1255 'fn' => 'previously FAILING test(s) removed O_o',
1256 'nf' => 'new FAILING test(s) :(',
1257 'ff' => 'still FAILING test(s) :(',
1260 $prevResults = array();
1262 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1263 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1264 foreach ( $res as $row ) {
1265 if ( !$this->parent->regex
1266 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1268 $prevResults[$row->ti_name] = $row->ti_success;
1272 $combined = array_keys( $this->results + $prevResults );
1274 # Determine breakdown by change type
1275 $breakdown = array();
1276 foreach ( $combined as $test ) {
1277 if ( !isset( $prevResults[$test] ) ) {
1279 } elseif ( $prevResults[$test] == 1 ) {
1281 } else /* if ( $prevResults[$test] == 0 )*/ {
1284 if ( !isset( $this->results[$test] ) ) {
1286 } elseif ( $this->results[$test] == 1 ) {
1288 } else /*if ( $this->results[$test] == 0 ) */ {
1291 $code = $before . $after;
1292 if ( isset( $table[$code] ) ) {
1293 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1298 foreach ( $table as $code => $label ) {
1299 if( !empty( $breakdown[$code] ) ) {
1300 $count = count($breakdown[$code]);
1301 printf( "\n%4d %s\n", $count, $label );
1302 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1303 print " * $differing_test_name [$statusInfo]\n";
1308 print "No previous test runs to compare against.\n";
1315 ** Returns a string giving information about when a test last had a status change.
1316 ** Could help to track down when regressions were introduced, as distinct from tests
1317 ** which have never passed (which are more change requests than regressions).
1319 private function getTestStatusInfo($testname, $after) {
1321 // If we're looking at a test that has just been removed, then say when it first appeared.
1322 if ( $after == 'n' ) {
1323 $changedRun = $this->db->selectField ( 'testitem',
1325 array( 'ti_name' => $testname ),
1327 $appear = $this->db->selectRow ( 'testrun',
1328 array( 'tr_date', 'tr_mw_version' ),
1329 array( 'tr_id' => $changedRun ),
1331 return "First recorded appearance: "
1332 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1333 . ", " . $appear->tr_mw_version;
1336 // Otherwise, this test has previous recorded results.
1337 // See when this test last had a different result to what we're seeing now.
1339 'ti_name' => $testname,
1340 'ti_success' => ($after == 'f' ? "1" : "0") );
1341 if ( $this->curRun ) {
1342 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1345 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1347 // If no record of ever having had a different result.
1348 if ( is_null ( $changedRun ) ) {
1349 if ($after == "f") {
1350 return "Has never passed";
1352 return "Has never failed";
1356 // Otherwise, we're looking at a test whose status has changed.
1357 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1358 // In this situation, give as much info as we can as to when it changed status.
1359 $pre = $this->db->selectRow ( 'testrun',
1360 array( 'tr_date', 'tr_mw_version' ),
1361 array( 'tr_id' => $changedRun ),
1363 $post = $this->db->selectRow ( 'testrun',
1364 array( 'tr_date', 'tr_mw_version' ),
1365 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1367 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1371 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1375 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1376 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1382 * Commit transaction and clean up for result recording
1385 $this->lb->commitMasterChanges();
1386 $this->lb->closeAll();
1392 class DbTestRecorder extends DbTestPreviewer {
1394 * Set up result recording; insert a record for the run with the date
1395 * and all that fun stuff
1398 global $wgDBtype, $wgDBprefix;
1401 if( ! $this->db->tableExists( 'testrun' )
1402 or ! $this->db->tableExists( 'testitem' ) )
1404 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1405 if ($wgDBtype === 'postgres')
1406 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1408 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1409 echo "OK, resuming.\n";
1414 $this->db->insert( 'testrun',
1416 'tr_date' => $this->db->timestamp(),
1417 'tr_mw_version' => SpecialVersion::getVersion(),
1418 'tr_php_version' => phpversion(),
1419 'tr_db_version' => $this->db->getServerVersion(),
1420 'tr_uname' => php_uname()
1423 if ($wgDBtype === 'postgres')
1424 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1426 $this->curRun = $this->db->insertId();
1430 * Record an individual test item's success or failure to the db
1431 * @param string $test
1432 * @param bool $result
1434 function record( $test, $result ) {
1435 parent::record( $test, $result );
1436 $this->db->insert( 'testitem',
1438 'ti_run' => $this->curRun,
1440 'ti_success' => $result ? 1 : 0,