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 (preg_match('/\\bdisabled\\b/i', $data['options'])
357 || !preg_match("/{$this->regex}/i", $data['test'])) {
363 $result = $this->runTest(
364 $this->chomp( $data['test'] ),
365 $this->chomp( $data['input'] ),
366 $this->chomp( $data['result'] ),
367 $this->chomp( $data['options'] ) );
368 $ok = $ok && $result;
369 $this->recorder->record( $this->chomp( $data['test'] ), $result );
374 if ( isset ($data[$section] ) ) {
375 wfDie( "duplicate section '$section' at line $n of $filename\n" );
377 $data[$section] = '';
381 $data[$section] .= $line;
384 if ( $this->showProgress ) {
391 * Get a Parser object
393 function getParser() {
394 global $wgParserConf;
395 $class = $wgParserConf['class'];
396 $parser = new $class( $wgParserConf );
397 foreach( $this->hooks as $tag => $callback ) {
398 $parser->setHook( $tag, $callback );
400 foreach( $this->functionHooks as $tag => $bits ) {
401 list( $callback, $flags ) = $bits;
402 $parser->setFunctionHook( $tag, $callback, $flags );
404 wfRunHooks( 'ParserTestParser', array( &$parser ) );
409 * Run a given wikitext input through a freshly-constructed wiki parser,
410 * and compare the output against the expected results.
411 * Prints status and explanatory messages to stdout.
413 * @param string $input Wikitext to try rendering
414 * @param string $result Result to output
417 private function runTest( $desc, $input, $result, $opts ) {
418 if( $this->showProgress ) {
419 $this->showTesting( $desc );
422 $this->setupGlobals($opts);
425 $options = ParserOptions::newFromUser( $user );
427 if (preg_match('/\\bmath\\b/i', $opts)) {
428 # XXX this should probably be done by the ParserOptions
429 $options->setUseTex(true);
433 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
437 $titleText = 'Parser test';
440 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
441 $parser = $this->getParser();
442 $title =& Title::makeTitle( NS_MAIN, $titleText );
445 if (preg_match('/\\bpst\\b/i', $opts)) {
446 $out = $parser->preSaveTransform( $input, $title, $user, $options );
447 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
448 $out = $parser->transformMsg( $input, $options );
449 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
450 $section = $matches[1];
451 $out = $parser->getSection( $input, $section );
452 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
453 $section = $matches[1];
454 $replace = $matches[2];
455 $out = $parser->replaceSection( $input, $section, $replace );
457 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
458 $out = $output->getText();
460 if (preg_match('/\\bill\\b/i', $opts)) {
461 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
462 } else if (preg_match('/\\bcat\\b/i', $opts)) {
464 $wgOut->addCategoryLinks($output->getCategories());
465 $cats = $wgOut->getCategoryLinks();
466 if ( isset( $cats['normal'] ) ) {
467 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
473 $result = $this->tidy($result);
476 $this->teardownGlobals();
478 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
479 return $this->showSuccess( $desc );
481 return $this->showFailure( $desc, $result, $out );
487 * Use a regex to find out the value of an option
488 * @param $regex A regex, the first group will be the value returned
489 * @param $opts Options line to look in
490 * @param $defaults Default value returned if the regex does not match
492 private static function getOptionValue( $regex, $opts, $default ) {
494 if( preg_match( $regex, $opts, $m ) ) {
502 * Set up the global variables for a consistent environment for each test.
503 * Ideally this should replace the global configuration entirely.
505 private function setupGlobals($opts = '') {
506 if( !isset( $this->uploadDir ) ) {
507 $this->uploadDir = $this->setupUploadDir();
510 # Find out values for some special options.
512 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
514 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
516 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
517 $linkHolderBatchSize =
518 self::getOptionValue( '/wgLinkHolderBatchSize=(\d+)/', $opts, 1000 );
521 'wgServer' => 'http://localhost',
522 'wgScript' => '/index.php',
523 'wgScriptPath' => '/',
524 'wgArticlePath' => '/wiki/$1',
525 'wgActionPaths' => array(),
526 'wgLocalFileRepo' => array(
527 'class' => 'LocalRepo',
529 'directory' => $this->uploadDir,
530 'url' => 'http://example.com/images',
532 'transformVia404' => false,
534 'wgEnableUploads' => true,
535 'wgStyleSheetPath' => '/skins',
536 'wgSitename' => 'MediaWiki',
537 'wgServerName' => 'Britney Spears',
538 'wgLanguageCode' => $lang,
539 'wgContLanguageCode' => $lang,
540 'wgDBprefix' => 'parsertest_',
541 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
543 'wgContLang' => null,
544 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
545 'wgMaxTocLevel' => $maxtoclevel,
546 'wgCapitalLinks' => true,
547 'wgNoFollowLinks' => true,
548 'wgThumbnailScriptPath' => false,
550 'wgLocaltimezone' => 'UTC',
551 'wgAllowExternalImages' => true,
552 'wgUseTidy' => false,
553 'wgDefaultLanguageVariant' => $variant,
554 'wgVariantArticlePath' => false,
555 'wgGroupPermissions' => array( '*' => array(
556 'createaccount' => true,
559 'createpage' => true,
560 'createtalk' => true,
562 'wgDefaultExternalStore' => array(),
563 'wgForeignFileRepos' => array(),
564 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
566 $this->savedGlobals = array();
567 foreach( $settings as $var => $val ) {
568 $this->savedGlobals[$var] = $GLOBALS[$var];
569 $GLOBALS[$var] = $val;
571 $langObj = Language::factory( $lang );
572 $GLOBALS['wgLang'] = $langObj;
573 $GLOBALS['wgContLang'] = $langObj;
574 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
576 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
579 $wgUser = new User();
583 * List of temporary tables to create, without prefix.
584 * Some of these probably aren't necessary.
586 private function listTables() {
588 $tables = array('user', 'page', 'page_restrictions',
589 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
590 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
591 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
592 'recentchanges', 'watchlist', 'math', 'interwiki',
593 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
594 'archive', 'user_groups', 'page_props', 'category'
597 if ($wgDBtype === 'mysql')
598 array_push( $tables, 'searchindex' );
600 // Allow extensions to add to the list of tables to duplicate;
601 // may be necessary if they hook into page save or other code
602 // which will require them while running tests.
603 wfRunHooks( 'ParserTestTables', array( &$tables ) );
609 * Set up a temporary set of wiki tables to work with for the tests.
610 * Currently this will only be done once per run, and any changes to
611 * the db will be visible to later tests in the run.
613 private function setupDatabase() {
615 if ( $this->databaseSetupDone ) {
618 if ( $wgDBprefix === 'parsertest_' ) {
619 throw new MWException( 'setupDatabase should be called before setupGlobals' );
621 $this->databaseSetupDone = true;
622 $this->oldTablePrefix = $wgDBprefix;
624 # CREATE TEMPORARY TABLE breaks if there is more than one server
625 if ( wfGetLB()->getServerCount() != 1 ) {
626 $this->useTemporaryTables = false;
629 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
631 $db = wfGetDB( DB_MASTER );
632 $tables = $this->listTables();
634 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
635 # Database that supports CREATE TABLE ... LIKE
637 if( $wgDBtype == 'postgres' ) {
638 $def = 'INCLUDING DEFAULTS';
642 foreach ($tables as $tbl) {
643 # Clean up from previous aborted run. So that table escaping
644 # works correctly across DB engines, we need to change the pre-
645 # fix back and forth so tableName() works right.
646 $this->changePrefix( $this->oldTablePrefix );
647 $oldTableName = $db->tableName( $tbl );
648 $this->changePrefix( 'parsertest_' );
649 $newTableName = $db->tableName( $tbl );
651 if ( $db->tableExists( $tbl ) ) {
652 $db->query("DROP TABLE $newTableName");
655 $db->query("CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)");
658 # Hack for MySQL versions < 4.1, which don't support
659 # "CREATE TABLE ... LIKE". Note that
660 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
661 # would not create the indexes we need....
663 # Note that we don't bother changing around the prefixes here be-
664 # cause we know we're using MySQL anyway.
665 foreach ($tables as $tbl) {
666 $oldTableName = $db->tableName( $tbl );
667 $res = $db->query("SHOW CREATE TABLE $oldTableName");
668 $row = $db->fetchRow($res);
670 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
671 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
672 if ($create === $create_tmp) {
673 # Couldn't do replacement
674 wfDie("could not create temporary table $tbl");
676 $db->query($create_tmp);
680 $this->changePrefix( 'parsertest_' );
682 # Hack: insert a few Wikipedia in-project interwiki prefixes,
683 # for testing inter-language links
684 $db->insert( 'interwiki', array(
685 array( 'iw_prefix' => 'wikipedia',
686 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
688 array( 'iw_prefix' => 'meatball',
689 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
691 array( 'iw_prefix' => 'zh',
692 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
694 array( 'iw_prefix' => 'es',
695 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
697 array( 'iw_prefix' => 'fr',
698 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
700 array( 'iw_prefix' => 'ru',
701 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
705 # Hack: Insert an image to work with
706 $db->insert( 'image', array(
707 'img_name' => 'Foobar.jpg',
709 'img_description' => 'Some lame file',
711 'img_user_text' => 'WikiSysop',
712 'img_timestamp' => $db->timestamp( '20010115123500' ),
716 'img_media_type' => MEDIATYPE_BITMAP,
717 'img_major_mime' => "image",
718 'img_minor_mime' => "jpeg",
719 'img_metadata' => serialize( array() ),
722 # Update certain things in site_stats
723 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
727 * Change the table prefix on all open DB connections/
729 protected function changePrefix( $prefix ) {
731 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
732 $wgDBprefix = $prefix;
735 public function changeLBPrefix( $lb, $prefix ) {
736 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
739 public function changeDBPrefix( $db, $prefix ) {
740 $db->tablePrefix( $prefix );
743 private function teardownDatabase() {
745 if ( !$this->databaseSetupDone ) {
748 $this->changePrefix( $this->oldTablePrefix );
749 $this->databaseSetupDone = false;
750 if ( $this->useTemporaryTables ) {
751 # Don't need to do anything
756 $tables = $this->listTables();
757 $db = wfGetDB( DB_MASTER );
758 foreach ( $tables as $table ) {
759 $db->query( "DROP TABLE `parsertest_$table`" );
764 * Create a dummy uploads directory which will contain a couple
765 * of files in order to pass existence tests.
766 * @return string The directory
768 private function setupUploadDir() {
770 if ( $this->keepUploads ) {
771 $dir = wfTempDir() . '/mwParser-images';
772 if ( is_dir( $dir ) ) {
776 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
779 wfDebug( "Creating upload directory $dir\n" );
780 if ( file_exists( $dir ) ) {
781 wfDebug( "Already exists!\n" );
785 mkdir( $dir . '/3' );
786 mkdir( $dir . '/3/3a' );
787 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
792 * Restore default values and perform any necessary clean-up
793 * after each test runs.
795 private function teardownGlobals() {
796 RepoGroup::destroySingleton();
797 LinkCache::singleton()->clear();
798 $GLOBALS['wgLang']->__destruct();
799 foreach( $this->savedGlobals as $var => $val ) {
800 $GLOBALS[$var] = $val;
802 if( isset( $this->uploadDir ) ) {
803 $this->teardownUploadDir( $this->uploadDir );
804 unset( $this->uploadDir );
809 * Remove the dummy uploads directory
811 private function teardownUploadDir( $dir ) {
812 if ( $this->keepUploads ) {
816 // delete the files first, then the dirs.
819 "$dir/3/3a/Foobar.jpg",
820 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
821 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
822 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
823 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
833 "$dir/thumb/3/3a/Foobar.jpg",
843 * Delete the specified files, if they exist.
844 * @param array $files full paths to files to delete.
846 private static function deleteFiles( $files ) {
847 foreach( $files as $file ) {
848 if( file_exists( $file ) ) {
855 * Delete the specified directories, if they exist. Must be empty.
856 * @param array $dirs full paths to directories to delete.
858 private static function deleteDirs( $dirs ) {
859 foreach( $dirs as $dir ) {
860 if( is_dir( $dir ) ) {
867 * "Running test $desc..."
869 protected function showTesting( $desc ) {
870 print "Running test $desc... ";
874 * Print a happy success message.
876 * @param string $desc The test name
879 protected function showSuccess( $desc ) {
880 if( $this->showProgress ) {
881 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
887 * Print a failure message and provide some explanatory output
888 * about what went wrong if so configured.
890 * @param string $desc The test name
891 * @param string $result Expected HTML output
892 * @param string $html Actual HTML output
895 protected function showFailure( $desc, $result, $html ) {
896 if( $this->showFailure ) {
897 if( !$this->showProgress ) {
898 # In quiet mode we didn't show the 'Testing' message before the
899 # test, in case it succeeded. Show it now:
900 $this->showTesting( $desc );
902 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
903 if ( $this->showOutput ) {
904 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
906 if( $this->showDiffs ) {
907 print $this->quickDiff( $result, $html );
908 if( !$this->wellFormed( $html ) ) {
909 print "XML error: $this->mXmlError\n";
917 * Run given strings through a diff and return the (colorized) output.
918 * Requires writable /tmp directory and a 'diff' command in the PATH.
920 * @param string $input
921 * @param string $output
922 * @param string $inFileTail Tailing for the input file name
923 * @param string $outFileTail Tailing for the output file name
926 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
927 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
929 $infile = "$prefix-$inFileTail";
930 $this->dumpToFile( $input, $infile );
932 $outfile = "$prefix-$outFileTail";
933 $this->dumpToFile( $output, $outfile );
935 $diff = `diff -au $infile $outfile`;
939 return $this->colorDiff( $diff );
943 * Write the given string to a file, adding a final newline.
945 * @param string $data
946 * @param string $filename
948 private function dumpToFile( $data, $filename ) {
949 $file = fopen( $filename, "wt" );
950 fwrite( $file, $data . "\n" );
955 * Colorize unified diff output if set for ANSI color output.
956 * Subtractions are colored blue, additions red.
958 * @param string $text
961 protected function colorDiff( $text ) {
963 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
964 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
965 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
970 * Show "Reading tests from ..."
972 * @param String $path
974 protected function showRunFile( $path ){
975 print $this->term->color( 1 ) .
976 "Reading tests from \"$path\"..." .
977 $this->term->reset() .
982 * Insert a temporary test article
983 * @param string $name the title, including any prefix
984 * @param string $text the article text
985 * @param int $line the input line number, for reporting errors
987 private function addArticle($name, $text, $line) {
988 $this->setupGlobals();
989 $title = Title::newFromText( $name );
990 if ( is_null($title) ) {
991 wfDie( "invalid title at line $line\n" );
994 $aid = $title->getArticleID( GAID_FOR_UPDATE );
996 wfDie( "duplicate article at line $line\n" );
999 $art = new Article($title);
1000 $art->insertNewArticle($text, '', false, false );
1001 $this->teardownGlobals();
1005 * Steal a callback function from the primary parser, save it for
1006 * application to our scary parser. If the hook is not installed,
1007 * die a painful dead to warn the others.
1008 * @param string $name
1010 private function requireHook( $name ) {
1012 if( isset( $wgParser->mTagHooks[$name] ) ) {
1013 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1015 wfDie( "This test suite requires the '$name' hook extension.\n" );
1020 * Steal a callback function from the primary parser, save it for
1021 * application to our scary parser. If the hook is not installed,
1022 * die a painful dead to warn the others.
1023 * @param string $name
1025 private function requireFunctionHook( $name ) {
1027 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1028 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1030 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1035 * Run the "tidy" command on text if the $wgUseTidy
1038 * @param string $text the text to tidy
1042 private function tidy( $text ) {
1045 $text = Parser::tidy($text);
1050 private function wellFormed( $text ) {
1052 Sanitizer::hackDocType() .
1057 $parser = xml_parser_create( "UTF-8" );
1059 # case folding violates XML standard, turn it off
1060 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1062 if( !xml_parse( $parser, $html, true ) ) {
1063 $err = xml_error_string( xml_get_error_code( $parser ) );
1064 $position = xml_get_current_byte_index( $parser );
1065 $fragment = $this->extractFragment( $html, $position );
1066 $this->mXmlError = "$err at byte $position:\n$fragment";
1067 xml_parser_free( $parser );
1070 xml_parser_free( $parser );
1074 private function extractFragment( $text, $position ) {
1075 $start = max( 0, $position - 10 );
1076 $before = $position - $start;
1078 $this->term->color( 34 ) .
1079 substr( $text, $start, $before ) .
1080 $this->term->color( 0 ) .
1081 $this->term->color( 31 ) .
1082 $this->term->color( 1 ) .
1083 substr( $text, $position, 1 ) .
1084 $this->term->color( 0 ) .
1085 $this->term->color( 34 ) .
1086 substr( $text, $position + 1, 9 ) .
1087 $this->term->color( 0 ) .
1089 $display = str_replace( "\n", ' ', $fragment );
1091 str_repeat( ' ', $before ) .
1092 $this->term->color( 31 ) .
1094 $this->term->color( 0 );
1095 return "$display\n$caret";
1099 class AnsiTermColorer {
1100 function __construct() {
1104 * Return ANSI terminal escape code for changing text attribs/color
1106 * @param string $color Semicolon-separated list of attribute/color codes
1109 public function color( $color ) {
1110 global $wgCommandLineDarkBg;
1111 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1112 return "\x1b[{$light}{$color}m";
1116 * Return ANSI terminal escape code for restoring default text attributes
1120 public function reset() {
1121 return $this->color( 0 );
1125 /* A colour-less terminal */
1126 class DummyTermColorer {
1127 public function color( $color ) {
1131 public function reset() {
1136 class TestRecorder {
1140 function __construct( $parent ) {
1141 $this->parent = $parent;
1142 $this->term = $parent->term;
1150 function record( $test, $result ) {
1152 $this->success += ($result ? 1 : 0);
1160 if( $this->total > 0 ) {
1161 $this->reportPercentage( $this->success, $this->total );
1163 wfDie( "No tests found.\n" );
1167 function reportPercentage( $success, $total ) {
1168 $ratio = wfPercent( 100 * $success / $total );
1169 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1170 if( $success == $total ) {
1171 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1173 $failed = $total - $success ;
1174 print $this->term->color( 31 ) . "$failed tests failed!";
1176 print $this->term->reset() . "\n";
1177 return ($success == $total);
1181 class DbTestPreviewer extends TestRecorder {
1182 protected $lb; ///< Database load balancer
1183 protected $db; ///< Database connection to the main DB
1184 protected $curRun; ///< run ID number for the current run
1185 protected $prevRun; ///< run ID number for the previous run, if any
1186 protected $results; ///< Result array
1189 * This should be called before the table prefix is changed
1191 function __construct( $parent ) {
1192 parent::__construct( $parent );
1193 $this->lb = wfGetLBFactory()->newMainLB();
1194 // This connection will have the wiki's table prefix, not parsertest_
1195 $this->db = $this->lb->getConnection( DB_MASTER );
1199 * Set up result recording; insert a record for the run with the date
1200 * and all that fun stuff
1203 global $wgDBtype, $wgDBprefix;
1206 if( ! $this->db->tableExists( 'testrun' )
1207 or ! $this->db->tableExists( 'testitem' ) )
1209 print "WARNING> `testrun` table not found in database.\n";
1210 $this->prevRun = false;
1212 // We'll make comparisons against the previous run later...
1213 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1215 $this->results = array();
1218 function record( $test, $result ) {
1219 parent::record( $test, $result );
1220 $this->results[$test] = $result;
1224 if( $this->prevRun ) {
1225 // f = fail, p = pass, n = nonexistent
1226 // codes show before then after
1228 'fp' => 'previously failing test(s) now PASSING! :)',
1229 'pn' => 'previously PASSING test(s) removed o_O',
1230 'np' => 'new PASSING test(s) :)',
1232 'pf' => 'previously passing test(s) now FAILING! :(',
1233 'fn' => 'previously FAILING test(s) removed O_o',
1234 'nf' => 'new FAILING test(s) :(',
1235 'ff' => 'still FAILING test(s) :(',
1238 $prevResults = array();
1240 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1241 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1242 foreach ( $res as $row ) {
1243 if ( !$this->parent->regex
1244 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1246 $prevResults[$row->ti_name] = $row->ti_success;
1250 $combined = array_keys( $this->results + $prevResults );
1252 # Determine breakdown by change type
1253 $breakdown = array();
1254 foreach ( $combined as $test ) {
1255 if ( !isset( $prevResults[$test] ) ) {
1257 } elseif ( $prevResults[$test] == 1 ) {
1259 } else /* if ( $prevResults[$test] == 0 )*/ {
1262 if ( !isset( $this->results[$test] ) ) {
1264 } elseif ( $this->results[$test] == 1 ) {
1266 } else /*if ( $this->results[$test] == 0 ) */ {
1269 $code = $before . $after;
1270 if ( isset( $table[$code] ) ) {
1271 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1276 foreach ( $table as $code => $label ) {
1277 if( !empty( $breakdown[$code] ) ) {
1278 $count = count($breakdown[$code]);
1279 printf( "\n%4d %s\n", $count, $label );
1280 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1281 print " * $differing_test_name [$statusInfo]\n";
1286 print "No previous test runs to compare against.\n";
1293 ** Returns a string giving information about when a test last had a status change.
1294 ** Could help to track down when regressions were introduced, as distinct from tests
1295 ** which have never passed (which are more change requests than regressions).
1297 private function getTestStatusInfo($testname, $after) {
1299 // If we're looking at a test that has just been removed, then say when it first appeared.
1300 if ( $after == 'n' ) {
1301 $changedRun = $this->db->selectField ( 'testitem',
1303 array( 'ti_name' => $testname ),
1305 $appear = $this->db->selectRow ( 'testrun',
1306 array( 'tr_date', 'tr_mw_version' ),
1307 array( 'tr_id' => $changedRun ),
1309 return "First recorded appearance: "
1310 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1311 . ", " . $appear->tr_mw_version;
1314 // Otherwise, this test has previous recorded results.
1315 // See when this test last had a different result to what we're seeing now.
1317 'ti_name' => $testname,
1318 'ti_success' => ($after == 'f' ? "1" : "0") );
1319 if ( $this->curRun ) {
1320 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1323 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1325 // If no record of ever having had a different result.
1326 if ( is_null ( $changedRun ) ) {
1327 if ($after == "f") {
1328 return "Has never passed";
1330 return "Has never failed";
1334 // Otherwise, we're looking at a test whose status has changed.
1335 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1336 // In this situation, give as much info as we can as to when it changed status.
1337 $pre = $this->db->selectRow ( 'testrun',
1338 array( 'tr_date', 'tr_mw_version' ),
1339 array( 'tr_id' => $changedRun ),
1341 $post = $this->db->selectRow ( 'testrun',
1342 array( 'tr_date', 'tr_mw_version' ),
1343 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1345 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1349 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1353 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1354 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1360 * Commit transaction and clean up for result recording
1363 $this->lb->commitMasterChanges();
1364 $this->lb->closeAll();
1370 class DbTestRecorder extends DbTestPreviewer {
1372 * Set up result recording; insert a record for the run with the date
1373 * and all that fun stuff
1376 global $wgDBtype, $wgDBprefix;
1379 if( ! $this->db->tableExists( 'testrun' )
1380 or ! $this->db->tableExists( 'testitem' ) )
1382 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1383 if ($wgDBtype === 'postgres')
1384 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1386 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1387 echo "OK, resuming.\n";
1392 $this->db->insert( 'testrun',
1394 'tr_date' => $this->db->timestamp(),
1395 'tr_mw_version' => SpecialVersion::getVersion(),
1396 'tr_php_version' => phpversion(),
1397 'tr_db_version' => $this->db->getServerVersion(),
1398 'tr_uname' => php_uname()
1401 if ($wgDBtype === 'postgres')
1402 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1404 $this->curRun = $this->db->insertId();
1408 * Record an individual test item's success or failure to the db
1409 * @param string $test
1410 * @param bool $result
1412 function record( $test, $result ) {
1413 parent::record( $test, $result );
1414 $this->db->insert( 'testitem',
1416 'ti_run' => $this->curRun,
1418 'ti_success' => $result ? 1 : 0,