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' );
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;
66 * Sets terminal colorization and diff/quick modes depending on OS and
67 * command-line options (--color and --quick).
69 public function ParserTest() {
72 # Only colorize output if stdout is a terminal.
73 $this->color = !wfIsWindows() && posix_isatty(1);
75 if( isset( $options['color'] ) ) {
76 switch( $options['color'] ) {
86 $this->term = $this->color
87 ? new AnsiTermColorer()
88 : new DummyTermColorer();
90 $this->showDiffs = !isset( $options['quick'] );
91 $this->showProgress = !isset( $options['quiet'] );
92 $this->showFailure = !(
93 isset( $options['quiet'] )
94 && ( isset( $options['record'] )
95 || isset( $options['compare'] ) ) ); // redundant output
97 $this->showOutput = isset( $options['show-output'] );
100 if (isset($options['regex'])) {
101 if ( isset( $options['record'] ) ) {
102 echo "Warning: --record cannot be used with --regex, disabling --record\n";
103 unset( $options['record'] );
105 $this->regex = $options['regex'];
111 if( isset( $options['record'] ) ) {
112 $this->recorder = new DbTestRecorder( $this );
113 } elseif( isset( $options['compare'] ) ) {
114 $this->recorder = new DbTestPreviewer( $this );
116 $this->recorder = new TestRecorder( $this );
118 $this->keepUploads = isset( $options['keep-uploads'] );
120 $this->hooks = array();
121 $this->functionHooks = array();
125 * Remove last character if it is a newline
127 private function chomp($s) {
128 if (substr($s, -1) === "\n") {
129 return substr($s, 0, -1);
137 * Run a series of tests listed in the given text files.
138 * Each test consists of a brief description, wikitext input,
139 * and the expected HTML output.
141 * Prints status updates on stdout and counts up the total
142 * number and percentage of passed tests.
144 * @param array of strings $filenames
145 * @return bool True if passed all tests, false if any tests failed.
147 public function runTestsFromFiles( $filenames ) {
148 $this->recorder->start();
149 $this->setupDatabase();
151 foreach( $filenames as $filename ) {
152 $ok = $this->runFile( $filename ) && $ok;
154 $this->teardownDatabase();
155 $this->recorder->report();
156 $this->recorder->end();
160 private function runFile( $filename ) {
161 $infile = fopen( $filename, 'rt' );
163 wfDie( "Couldn't open $filename\n" );
166 $relative = wfRelativePath( $filename, $IP );
167 $this->showRunFile( $relative );
174 while( false !== ($line = fgets( $infile ) ) ) {
177 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
178 $section = strtolower( $matches[1] );
179 if( $section == 'endarticle') {
180 if( !isset( $data['text'] ) ) {
181 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
183 if( !isset( $data['article'] ) ) {
184 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
186 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
191 if( $section == 'endhooks' ) {
192 if( !isset( $data['hooks'] ) ) {
193 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
195 foreach( explode( "\n", $data['hooks'] ) as $line ) {
196 $line = trim( $line );
198 $this->requireHook( $line );
205 if( $section == 'endfunctionhooks' ) {
206 if( !isset( $data['functionhooks'] ) ) {
207 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
209 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
210 $line = trim( $line );
212 $this->requireFunctionHook( $line );
219 if( $section == 'end' ) {
220 if( !isset( $data['test'] ) ) {
221 wfDie( "'end' without 'test' at line $n of $filename\n" );
223 if( !isset( $data['input'] ) ) {
224 wfDie( "'end' without 'input' at line $n of $filename\n" );
226 if( !isset( $data['result'] ) ) {
227 wfDie( "'end' without 'result' at line $n of $filename\n" );
229 if( !isset( $data['options'] ) ) {
230 $data['options'] = '';
233 $data['options'] = $this->chomp( $data['options'] );
235 if (preg_match('/\\bdisabled\\b/i', $data['options'])
236 || !preg_match("/{$this->regex}/i", $data['test'])) {
242 $result = $this->runTest(
243 $this->chomp( $data['test'] ),
244 $this->chomp( $data['input'] ),
245 $this->chomp( $data['result'] ),
246 $this->chomp( $data['options'] ) );
247 $ok = $ok && $result;
248 $this->recorder->record( $this->chomp( $data['test'] ), $result );
253 if ( isset ($data[$section] ) ) {
254 wfDie( "duplicate section '$section' at line $n of $filename\n" );
256 $data[$section] = '';
260 $data[$section] .= $line;
263 if ( $this->showProgress ) {
270 * Run a given wikitext input through a freshly-constructed wiki parser,
271 * and compare the output against the expected results.
272 * Prints status and explanatory messages to stdout.
274 * @param string $input Wikitext to try rendering
275 * @param string $result Result to output
278 private function runTest( $desc, $input, $result, $opts ) {
279 global $wgParserConf;
280 if( $this->showProgress ) {
281 $this->showTesting( $desc );
284 $this->setupGlobals($opts);
287 $options = ParserOptions::newFromUser( $user );
289 if (preg_match('/\\bmath\\b/i', $opts)) {
290 # XXX this should probably be done by the ParserOptions
291 $options->setUseTex(true);
295 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
299 $titleText = 'Parser test';
302 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
304 $class = $wgParserConf['class'];
305 $parser = new $class( $wgParserConf );
306 foreach( $this->hooks as $tag => $callback ) {
307 $parser->setHook( $tag, $callback );
309 foreach( $this->functionHooks as $tag => $bits ) {
310 list( $callback, $flags ) = $bits;
311 $parser->setFunctionHook( $tag, $callback, $flags );
313 wfRunHooks( 'ParserTestParser', array( &$parser ) );
315 $title =& Title::makeTitle( NS_MAIN, $titleText );
318 if (preg_match('/\\bpst\\b/i', $opts)) {
319 $out = $parser->preSaveTransform( $input, $title, $user, $options );
320 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
321 $out = $parser->transformMsg( $input, $options );
322 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
323 $section = $matches[1];
324 $out = $parser->getSection( $input, $section );
325 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
326 $section = $matches[1];
327 $replace = $matches[2];
328 $out = $parser->replaceSection( $input, $section, $replace );
330 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
331 $out = $output->getText();
333 if (preg_match('/\\bill\\b/i', $opts)) {
334 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
335 } else if (preg_match('/\\bcat\\b/i', $opts)) {
337 $wgOut->addCategoryLinks($output->getCategories());
338 $cats = $wgOut->getCategoryLinks();
339 if ( isset( $cats['normal'] ) ) {
340 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
346 $result = $this->tidy($result);
349 $this->teardownGlobals();
351 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
352 return $this->showSuccess( $desc );
354 return $this->showFailure( $desc, $result, $out );
360 * Use a regex to find out the value of an option
361 * @param $regex A regex, the first group will be the value returned
362 * @param $opts Options line to look in
363 * @param $defaults Default value returned if the regex does not match
365 private static function getOptionValue( $regex, $opts, $default ) {
367 if( preg_match( $regex, $opts, $m ) ) {
375 * Set up the global variables for a consistent environment for each test.
376 * Ideally this should replace the global configuration entirely.
378 private function setupGlobals($opts = '') {
379 if( !isset( $this->uploadDir ) ) {
380 $this->uploadDir = $this->setupUploadDir();
383 # Find out values for some special options.
385 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
387 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
389 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
392 'wgServer' => 'http://localhost',
393 'wgScript' => '/index.php',
394 'wgScriptPath' => '/',
395 'wgArticlePath' => '/wiki/$1',
396 'wgActionPaths' => array(),
397 'wgLocalFileRepo' => array(
398 'class' => 'LocalRepo',
400 'directory' => $this->uploadDir,
401 'url' => 'http://example.com/images',
403 'transformVia404' => false,
405 'wgEnableUploads' => true,
406 'wgStyleSheetPath' => '/skins',
407 'wgSitename' => 'MediaWiki',
408 'wgServerName' => 'Britney Spears',
409 'wgLanguageCode' => $lang,
410 'wgContLanguageCode' => $lang,
411 'wgDBprefix' => 'parsertest_',
412 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
414 'wgContLang' => null,
415 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
416 'wgMaxTocLevel' => $maxtoclevel,
417 'wgCapitalLinks' => true,
418 'wgNoFollowLinks' => true,
419 'wgThumbnailScriptPath' => false,
421 'wgLocaltimezone' => 'UTC',
422 'wgAllowExternalImages' => true,
423 'wgUseTidy' => false,
424 'wgDefaultLanguageVariant' => $variant,
425 'wgVariantArticlePath' => false,
426 'wgGroupPermissions' => array( '*' => array(
427 'createaccount' => true,
430 'createpage' => true,
431 'createtalk' => true,
433 'wgDefaultExternalStore' => array(),
434 'wgForeignFileRepos' => array(),
436 $this->savedGlobals = array();
437 foreach( $settings as $var => $val ) {
438 $this->savedGlobals[$var] = $GLOBALS[$var];
439 $GLOBALS[$var] = $val;
441 $langObj = Language::factory( $lang );
442 $GLOBALS['wgLang'] = $langObj;
443 $GLOBALS['wgContLang'] = $langObj;
445 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
448 $wgUser = new User();
452 * List of temporary tables to create, without prefix.
453 * Some of these probably aren't necessary.
455 private function listTables() {
457 $tables = array('user', 'page', 'page_restrictions',
458 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
459 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
460 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
461 'recentchanges', 'watchlist', 'math', 'interwiki',
462 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
463 'archive', 'user_groups', 'page_props', 'category'
466 if ($wgDBtype === 'mysql')
467 array_push( $tables, 'searchindex' );
469 // Allow extensions to add to the list of tables to duplicate;
470 // may be necessary if they hook into page save or other code
471 // which will require them while running tests.
472 wfRunHooks( 'ParserTestTables', array( &$tables ) );
478 * Set up a temporary set of wiki tables to work with for the tests.
479 * Currently this will only be done once per run, and any changes to
480 * the db will be visible to later tests in the run.
482 private function setupDatabase() {
484 if ( $this->databaseSetupDone ) {
487 if ( $wgDBprefix === 'parsertest_' ) {
488 throw new MWException( 'setupDatabase should be called before setupGlobals' );
490 $this->databaseSetupDone = true;
491 $this->oldTablePrefix = $wgDBprefix;
493 # CREATE TEMPORARY TABLE breaks if there is more than one server
494 if ( wfGetLB()->getServerCount() != 1 ) {
495 $this->useTemporaryTables = false;
498 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
500 $db = wfGetDB( DB_MASTER );
501 $tables = $this->listTables();
503 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
504 # Database that supports CREATE TABLE ... LIKE
506 if( $wgDBtype == 'postgres' ) {
507 $def = 'INCLUDING DEFAULTS';
511 foreach ($tables as $tbl) {
512 # Clean up from previous aborted run. So that table escaping
513 # works correctly across DB engines, we need to change the pre-
514 # fix back and forth so tableName() works right.
515 $this->changePrefix( $this->oldTablePrefix );
516 $oldTableName = $db->tableName( $tbl );
517 $this->changePrefix( 'parsertest_' );
518 $newTableName = $db->tableName( $tbl );
520 if ( $db->tableExists( $tbl ) ) {
521 $db->query("DROP TABLE $newTableName");
524 $db->query("CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)");
527 # Hack for MySQL versions < 4.1, which don't support
528 # "CREATE TABLE ... LIKE". Note that
529 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
530 # would not create the indexes we need....
532 # Note that we don't bother changing around the prefixes here be-
533 # cause we know we're using MySQL anyway.
534 foreach ($tables as $tbl) {
535 $oldTableName = $db->tableName( $tbl );
536 $res = $db->query("SHOW CREATE TABLE $oldTableName");
537 $row = $db->fetchRow($res);
539 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
540 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
541 if ($create === $create_tmp) {
542 # Couldn't do replacement
543 wfDie("could not create temporary table $tbl");
545 $db->query($create_tmp);
549 $this->changePrefix( 'parsertest_' );
551 # Hack: insert a few Wikipedia in-project interwiki prefixes,
552 # for testing inter-language links
553 $db->insert( 'interwiki', array(
554 array( 'iw_prefix' => 'Wikipedia',
555 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
557 array( 'iw_prefix' => 'MeatBall',
558 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
560 array( 'iw_prefix' => 'zh',
561 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
563 array( 'iw_prefix' => 'es',
564 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
566 array( 'iw_prefix' => 'fr',
567 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
569 array( 'iw_prefix' => 'ru',
570 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
574 # Hack: Insert an image to work with
575 $db->insert( 'image', array(
576 'img_name' => 'Foobar.jpg',
578 'img_description' => 'Some lame file',
580 'img_user_text' => 'WikiSysop',
581 'img_timestamp' => $db->timestamp( '20010115123500' ),
585 'img_media_type' => MEDIATYPE_BITMAP,
586 'img_major_mime' => "image",
587 'img_minor_mime' => "jpeg",
588 'img_metadata' => serialize( array() ),
591 # Update certain things in site_stats
592 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
596 * Change the table prefix on all open DB connections/
598 protected function changePrefix( $prefix ) {
600 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
601 $wgDBprefix = $prefix;
604 public function changeLBPrefix( $lb, $prefix ) {
605 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
608 public function changeDBPrefix( $db, $prefix ) {
609 $db->tablePrefix( $prefix );
612 private function teardownDatabase() {
614 if ( !$this->databaseSetupDone ) {
617 $this->changePrefix( $this->oldTablePrefix );
618 $this->databaseSetupDone = false;
619 if ( $this->useTemporaryTables ) {
620 # Don't need to do anything
624 $tables = $this->listTables();
625 $db = wfGetDB( DB_MASTER );
626 foreach ( $tables as $table ) {
627 $db->query( "DROP TABLE `parsertest_$table`" );
632 * Create a dummy uploads directory which will contain a couple
633 * of files in order to pass existence tests.
634 * @return string The directory
636 private function setupUploadDir() {
638 if ( $this->keepUploads ) {
639 $dir = wfTempDir() . '/mwParser-images';
640 if ( is_dir( $dir ) ) {
644 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
647 wfDebug( "Creating upload directory $dir\n" );
649 mkdir( $dir . '/3' );
650 mkdir( $dir . '/3/3a' );
651 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
656 * Restore default values and perform any necessary clean-up
657 * after each test runs.
659 private function teardownGlobals() {
660 RepoGroup::destroySingleton();
661 foreach( $this->savedGlobals as $var => $val ) {
662 $GLOBALS[$var] = $val;
664 if( isset( $this->uploadDir ) ) {
665 $this->teardownUploadDir( $this->uploadDir );
666 unset( $this->uploadDir );
671 * Remove the dummy uploads directory
673 private function teardownUploadDir( $dir ) {
674 if ( $this->keepUploads ) {
678 // delete the files first, then the dirs.
681 "$dir/3/3a/Foobar.jpg",
682 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
683 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
684 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
685 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
695 "$dir/thumb/3/3a/Foobar.jpg",
705 * Delete the specified files, if they exist.
706 * @param array $files full paths to files to delete.
708 private static function deleteFiles( $files ) {
709 foreach( $files as $file ) {
710 if( file_exists( $file ) ) {
717 * Delete the specified directories, if they exist. Must be empty.
718 * @param array $dirs full paths to directories to delete.
720 private static function deleteDirs( $dirs ) {
721 foreach( $dirs as $dir ) {
722 if( is_dir( $dir ) ) {
729 * "Running test $desc..."
731 protected function showTesting( $desc ) {
732 print "Running test $desc... ";
736 * Print a happy success message.
738 * @param string $desc The test name
741 protected function showSuccess( $desc ) {
742 if( $this->showProgress ) {
743 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
749 * Print a failure message and provide some explanatory output
750 * about what went wrong if so configured.
752 * @param string $desc The test name
753 * @param string $result Expected HTML output
754 * @param string $html Actual HTML output
757 protected function showFailure( $desc, $result, $html ) {
758 if( $this->showFailure ) {
759 if( !$this->showProgress ) {
760 # In quiet mode we didn't show the 'Testing' message before the
761 # test, in case it succeeded. Show it now:
762 $this->showTesting( $desc );
764 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
765 if ( $this->showOutput ) {
766 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
768 if( $this->showDiffs ) {
769 print $this->quickDiff( $result, $html );
770 if( !$this->wellFormed( $html ) ) {
771 print "XML error: $this->mXmlError\n";
779 * Run given strings through a diff and return the (colorized) output.
780 * Requires writable /tmp directory and a 'diff' command in the PATH.
782 * @param string $input
783 * @param string $output
784 * @param string $inFileTail Tailing for the input file name
785 * @param string $outFileTail Tailing for the output file name
788 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
789 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
791 $infile = "$prefix-$inFileTail";
792 $this->dumpToFile( $input, $infile );
794 $outfile = "$prefix-$outFileTail";
795 $this->dumpToFile( $output, $outfile );
797 $diff = `diff -au $infile $outfile`;
801 return $this->colorDiff( $diff );
805 * Write the given string to a file, adding a final newline.
807 * @param string $data
808 * @param string $filename
810 private function dumpToFile( $data, $filename ) {
811 $file = fopen( $filename, "wt" );
812 fwrite( $file, $data . "\n" );
817 * Colorize unified diff output if set for ANSI color output.
818 * Subtractions are colored blue, additions red.
820 * @param string $text
823 protected function colorDiff( $text ) {
825 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
826 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
827 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
832 * Show "Reading tests from ..."
834 * @param String $path
836 protected function showRunFile( $path ){
837 print $this->term->color( 1 ) .
838 "Reading tests from \"$path\"..." .
839 $this->term->reset() .
844 * Insert a temporary test article
845 * @param string $name the title, including any prefix
846 * @param string $text the article text
847 * @param int $line the input line number, for reporting errors
849 private function addArticle($name, $text, $line) {
850 $this->setupGlobals();
851 $title = Title::newFromText( $name );
852 if ( is_null($title) ) {
853 wfDie( "invalid title at line $line\n" );
856 $aid = $title->getArticleID( GAID_FOR_UPDATE );
858 wfDie( "duplicate article at line $line\n" );
861 $art = new Article($title);
862 $art->insertNewArticle($text, '', false, false );
863 $this->teardownGlobals();
867 * Steal a callback function from the primary parser, save it for
868 * application to our scary parser. If the hook is not installed,
869 * die a painful dead to warn the others.
870 * @param string $name
872 private function requireHook( $name ) {
874 if( isset( $wgParser->mTagHooks[$name] ) ) {
875 $this->hooks[$name] = $wgParser->mTagHooks[$name];
877 wfDie( "This test suite requires the '$name' hook extension.\n" );
882 * Steal a callback function from the primary parser, save it for
883 * application to our scary parser. If the hook is not installed,
884 * die a painful dead to warn the others.
885 * @param string $name
887 private function requireFunctionHook( $name ) {
889 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
890 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
892 wfDie( "This test suite requires the '$name' function hook extension.\n" );
897 * Run the "tidy" command on text if the $wgUseTidy
900 * @param string $text the text to tidy
904 private function tidy( $text ) {
907 $text = Parser::tidy($text);
912 private function wellFormed( $text ) {
914 Sanitizer::hackDocType() .
919 $parser = xml_parser_create( "UTF-8" );
921 # case folding violates XML standard, turn it off
922 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
924 if( !xml_parse( $parser, $html, true ) ) {
925 $err = xml_error_string( xml_get_error_code( $parser ) );
926 $position = xml_get_current_byte_index( $parser );
927 $fragment = $this->extractFragment( $html, $position );
928 $this->mXmlError = "$err at byte $position:\n$fragment";
929 xml_parser_free( $parser );
932 xml_parser_free( $parser );
936 private function extractFragment( $text, $position ) {
937 $start = max( 0, $position - 10 );
938 $before = $position - $start;
940 $this->term->color( 34 ) .
941 substr( $text, $start, $before ) .
942 $this->term->color( 0 ) .
943 $this->term->color( 31 ) .
944 $this->term->color( 1 ) .
945 substr( $text, $position, 1 ) .
946 $this->term->color( 0 ) .
947 $this->term->color( 34 ) .
948 substr( $text, $position + 1, 9 ) .
949 $this->term->color( 0 ) .
951 $display = str_replace( "\n", ' ', $fragment );
953 str_repeat( ' ', $before ) .
954 $this->term->color( 31 ) .
956 $this->term->color( 0 );
957 return "$display\n$caret";
961 class AnsiTermColorer {
962 function __construct() {
966 * Return ANSI terminal escape code for changing text attribs/color
968 * @param string $color Semicolon-separated list of attribute/color codes
971 public function color( $color ) {
972 global $wgCommandLineDarkBg;
973 $light = $wgCommandLineDarkBg ? "1;" : "0;";
974 return "\x1b[{$light}{$color}m";
978 * Return ANSI terminal escape code for restoring default text attributes
982 public function reset() {
983 return $this->color( 0 );
987 /* A colour-less terminal */
988 class DummyTermColorer {
989 public function color( $color ) {
993 public function reset() {
1002 function __construct( $parent ) {
1003 $this->parent = $parent;
1004 $this->term = $parent->term;
1012 function record( $test, $result ) {
1014 $this->success += ($result ? 1 : 0);
1022 if( $this->total > 0 ) {
1023 $this->reportPercentage( $this->success, $this->total );
1025 wfDie( "No tests found.\n" );
1029 function reportPercentage( $success, $total ) {
1030 $ratio = wfPercent( 100 * $success / $total );
1031 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1032 if( $success == $total ) {
1033 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1035 $failed = $total - $success ;
1036 print $this->term->color( 31 ) . "$failed tests failed!";
1038 print $this->term->reset() . "\n";
1039 return ($success == $total);
1043 class DbTestPreviewer extends TestRecorder {
1044 protected $lb; ///< Database load balancer
1045 protected $db; ///< Database connection to the main DB
1046 protected $curRun; ///< run ID number for the current run
1047 protected $prevRun; ///< run ID number for the previous run, if any
1048 protected $results; ///< Result array
1051 * This should be called before the table prefix is changed
1053 function __construct( $parent ) {
1054 parent::__construct( $parent );
1055 $this->lb = wfGetLBFactory()->newMainLB();
1056 // This connection will have the wiki's table prefix, not parsertest_
1057 $this->db = $this->lb->getConnection( DB_MASTER );
1061 * Set up result recording; insert a record for the run with the date
1062 * and all that fun stuff
1065 global $wgDBtype, $wgDBprefix;
1068 if( ! $this->db->tableExists( 'testrun' )
1069 or ! $this->db->tableExists( 'testitem' ) )
1071 print "WARNING> `testrun` table not found in database.\n";
1072 $this->prevRun = false;
1074 // We'll make comparisons against the previous run later...
1075 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1077 $this->results = array();
1080 function record( $test, $result ) {
1081 parent::record( $test, $result );
1082 $this->results[$test] = $result;
1086 if( $this->prevRun ) {
1087 // f = fail, p = pass, n = nonexistent
1088 // codes show before then after
1090 'fp' => 'previously failing test(s) now PASSING! :)',
1091 'pn' => 'previously PASSING test(s) removed o_O',
1092 'np' => 'new PASSING test(s) :)',
1094 'pf' => 'previously passing test(s) now FAILING! :(',
1095 'fn' => 'previously FAILING test(s) removed O_o',
1096 'nf' => 'new FAILING test(s) :(',
1097 'ff' => 'still FAILING test(s) :(',
1100 $prevResults = array();
1102 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1103 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1104 foreach ( $res as $row ) {
1105 if ( !$this->parent->regex
1106 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1108 $prevResults[$row->ti_name] = $row->ti_success;
1112 $combined = array_keys( $this->results + $prevResults );
1114 # Determine breakdown by change type
1115 $breakdown = array();
1116 foreach ( $combined as $test ) {
1117 if ( !isset( $prevResults[$test] ) ) {
1119 } elseif ( $prevResults[$test] == 1 ) {
1121 } else /* if ( $prevResults[$test] == 0 )*/ {
1124 if ( !isset( $this->results[$test] ) ) {
1126 } elseif ( $this->results[$test] == 1 ) {
1128 } else /*if ( $this->results[$test] == 0 ) */ {
1131 $code = $before . $after;
1132 if ( isset( $table[$code] ) ) {
1133 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1138 foreach ( $table as $code => $label ) {
1139 if( !empty( $breakdown[$code] ) ) {
1140 $count = count($breakdown[$code]);
1141 printf( "\n%4d %s\n", $count, $label );
1142 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1143 print " * $differing_test_name [$statusInfo]\n";
1148 print "No previous test runs to compare against.\n";
1155 ** Returns a string giving information about when a test last had a status change.
1156 ** Could help to track down when regressions were introduced, as distinct from tests
1157 ** which have never passed (which are more change requests than regressions).
1159 private function getTestStatusInfo($testname, $after) {
1161 // If we're looking at a test that has just been removed, then say when it first appeared.
1162 if ( $after == 'n' ) {
1163 $changedRun = $this->db->selectField ( 'testitem',
1165 array( 'ti_name' => $testname ),
1167 $appear = $this->db->selectRow ( 'testrun',
1168 array( 'tr_date', 'tr_mw_version' ),
1169 array( 'tr_id' => $changedRun ),
1171 return "First recorded appearance: "
1172 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1173 . ", " . $appear->tr_mw_version;
1176 // Otherwise, this test has previous recorded results.
1177 // See when this test last had a different result to what we're seeing now.
1179 'ti_name' => $testname,
1180 'ti_success' => ($after == 'f' ? "1" : "0") );
1181 if ( $this->curRun ) {
1182 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1185 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1187 // If no record of ever having had a different result.
1188 if ( is_null ( $changedRun ) ) {
1189 if ($after == "f") {
1190 return "Has never passed";
1192 return "Has never failed";
1196 // Otherwise, we're looking at a test whose status has changed.
1197 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1198 // In this situation, give as much info as we can as to when it changed status.
1199 $pre = $this->db->selectRow ( 'testrun',
1200 array( 'tr_date', 'tr_mw_version' ),
1201 array( 'tr_id' => $changedRun ),
1203 $post = $this->db->selectRow ( 'testrun',
1204 array( 'tr_date', 'tr_mw_version' ),
1205 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1207 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1211 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1215 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1216 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1222 * Commit transaction and clean up for result recording
1225 $this->lb->commitMasterChanges();
1226 $this->lb->closeAll();
1232 class DbTestRecorder extends DbTestPreviewer {
1234 * Set up result recording; insert a record for the run with the date
1235 * and all that fun stuff
1238 global $wgDBtype, $wgDBprefix;
1241 if( ! $this->db->tableExists( 'testrun' )
1242 or ! $this->db->tableExists( 'testitem' ) )
1244 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1245 if ($wgDBtype === 'postgres')
1246 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1248 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1249 echo "OK, resuming.\n";
1254 $this->db->insert( 'testrun',
1256 'tr_date' => $this->db->timestamp(),
1257 'tr_mw_version' => SpecialVersion::getVersion(),
1258 'tr_php_version' => phpversion(),
1259 'tr_db_version' => $this->db->getServerVersion(),
1260 'tr_uname' => php_uname()
1263 if ($wgDBtype === 'postgres')
1264 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1266 $this->curRun = $this->db->insertId();
1270 * Record an individual test item's success or failure to the db
1271 * @param string $test
1272 * @param bool $result
1274 function record( $test, $result ) {
1275 parent::record( $test, $result );
1276 $this->db->insert( 'testitem',
1278 'ti_run' => $this->curRun,
1280 'ti_success' => $result ? 1 : 0,