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 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
342 $result = $this->tidy($result);
345 $this->teardownGlobals();
347 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
348 return $this->showSuccess( $desc );
350 return $this->showFailure( $desc, $result, $out );
356 * Use a regex to find out the value of an option
357 * @param $regex A regex, the first group will be the value returned
358 * @param $opts Options line to look in
359 * @param $defaults Default value returned if the regex does not match
361 private static function getOptionValue( $regex, $opts, $default ) {
363 if( preg_match( $regex, $opts, $m ) ) {
371 * Set up the global variables for a consistent environment for each test.
372 * Ideally this should replace the global configuration entirely.
374 private function setupGlobals($opts = '') {
375 if( !isset( $this->uploadDir ) ) {
376 $this->uploadDir = $this->setupUploadDir();
379 # Find out values for some special options.
381 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
383 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
385 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
388 'wgServer' => 'http://localhost',
389 'wgScript' => '/index.php',
390 'wgScriptPath' => '/',
391 'wgArticlePath' => '/wiki/$1',
392 'wgActionPaths' => array(),
393 'wgLocalFileRepo' => array(
394 'class' => 'LocalRepo',
396 'directory' => $this->uploadDir,
397 'url' => 'http://example.com/images',
399 'transformVia404' => false,
401 'wgEnableUploads' => true,
402 'wgStyleSheetPath' => '/skins',
403 'wgSitename' => 'MediaWiki',
404 'wgServerName' => 'Britney Spears',
405 'wgLanguageCode' => $lang,
406 'wgContLanguageCode' => $lang,
407 'wgDBprefix' => 'parsertest_',
408 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
410 'wgContLang' => null,
411 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
412 'wgMaxTocLevel' => $maxtoclevel,
413 'wgCapitalLinks' => true,
414 'wgNoFollowLinks' => true,
415 'wgThumbnailScriptPath' => false,
417 'wgLocaltimezone' => 'UTC',
418 'wgAllowExternalImages' => true,
419 'wgUseTidy' => false,
420 'wgDefaultLanguageVariant' => $variant,
421 'wgVariantArticlePath' => false,
422 'wgGroupPermissions' => array( '*' => array(
423 'createaccount' => true,
426 'createpage' => true,
427 'createtalk' => true,
429 'wgDefaultExternalStore' => array(),
430 'wgForeignFileRepos' => array(),
432 $this->savedGlobals = array();
433 foreach( $settings as $var => $val ) {
434 $this->savedGlobals[$var] = $GLOBALS[$var];
435 $GLOBALS[$var] = $val;
437 $langObj = Language::factory( $lang );
438 $GLOBALS['wgLang'] = $langObj;
439 $GLOBALS['wgContLang'] = $langObj;
441 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
444 $wgUser = new User();
448 * List of temporary tables to create, without prefix.
449 * Some of these probably aren't necessary.
451 private function listTables() {
453 $tables = array('user', 'page', 'page_restrictions',
454 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
455 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
456 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
457 'recentchanges', 'watchlist', 'math', 'interwiki',
458 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
459 'archive', 'user_groups', 'page_props', 'category'
462 if ($wgDBtype === 'mysql')
463 array_push( $tables, 'searchindex' );
465 // Allow extensions to add to the list of tables to duplicate;
466 // may be necessary if they hook into page save or other code
467 // which will require them while running tests.
468 wfRunHooks( 'ParserTestTables', array( &$tables ) );
474 * Set up a temporary set of wiki tables to work with for the tests.
475 * Currently this will only be done once per run, and any changes to
476 * the db will be visible to later tests in the run.
478 private function setupDatabase() {
480 if ( $this->databaseSetupDone ) {
483 if ( $wgDBprefix === 'parsertest_' ) {
484 throw new MWException( 'setupDatabase should be called before setupGlobals' );
486 $this->databaseSetupDone = true;
488 # CREATE TEMPORARY TABLE breaks if there is more than one server
489 if ( wfGetLB()->getServerCount() != 1 ) {
490 $this->useTemporaryTables = false;
493 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
495 $db = wfGetDB( DB_MASTER );
496 $tables = $this->listTables();
498 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
499 # Database that supports CREATE TABLE ... LIKE
501 if( $wgDBtype == 'postgres' ) {
502 $def = 'INCLUDING DEFAULTS';
506 foreach ($tables as $tbl) {
507 $oldTableName = $db->tableName( $tbl );
508 # Clean up from previous aborted run
509 if ( $db->tableExists( "`parsertest_$tbl`" ) ) {
510 $db->query("DROP TABLE `parsertest_$tbl`");
513 $db->query("CREATE $temporary TABLE `parsertest_$tbl` (LIKE $oldTableName $def)");
516 # Hack for MySQL versions < 4.1, which don't support
517 # "CREATE TABLE ... LIKE". Note that
518 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
519 # would not create the indexes we need....
520 foreach ($tables as $tbl) {
521 $oldTableName = $db->tableName( $tbl );
522 $res = $db->query("SHOW CREATE TABLE $oldTableName");
523 $row = $db->fetchRow($res);
525 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
526 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
527 if ($create === $create_tmp) {
528 # Couldn't do replacement
529 wfDie("could not create temporary table $tbl");
531 $db->query($create_tmp);
535 # Hack: insert a few Wikipedia in-project interwiki prefixes,
536 # for testing inter-language links
537 $db->insert( '`parsertest_interwiki`', array(
538 array( 'iw_prefix' => 'Wikipedia',
539 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
541 array( 'iw_prefix' => 'MeatBall',
542 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
544 array( 'iw_prefix' => 'zh',
545 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
547 array( 'iw_prefix' => 'es',
548 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
550 array( 'iw_prefix' => 'fr',
551 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
553 array( 'iw_prefix' => 'ru',
554 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
558 # Hack: Insert an image to work with
559 $db->insert( '`parsertest_image`', array(
560 'img_name' => 'Foobar.jpg',
562 'img_description' => 'Some lame file',
564 'img_user_text' => 'WikiSysop',
565 'img_timestamp' => $db->timestamp( '20010115123500' ),
569 'img_media_type' => MEDIATYPE_BITMAP,
570 'img_major_mime' => "image",
571 'img_minor_mime' => "jpeg",
572 'img_metadata' => serialize( array() ),
575 # Update certain things in site_stats
576 $db->insert( '`parsertest_site_stats`', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
578 # Change the table prefix
579 $this->oldTablePrefix = $wgDBprefix;
580 $this->changePrefix( 'parsertest_' );
584 * Change the table prefix on all open DB connections/
586 protected function changePrefix( $prefix ) {
588 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
589 $wgDBprefix = $prefix;
592 public function changeLBPrefix( $lb, $prefix ) {
593 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
596 public function changeDBPrefix( $db, $prefix ) {
597 $db->tablePrefix( $prefix );
600 private function teardownDatabase() {
602 if ( !$this->databaseSetupDone ) {
605 $this->changePrefix( $this->oldTablePrefix );
606 $this->databaseSetupDone = false;
607 if ( $this->useTemporaryTables ) {
608 # Don't need to do anything
612 $tables = $this->listTables();
613 $db = wfGetDB( DB_MASTER );
614 foreach ( $tables as $table ) {
615 $db->query( "DROP TABLE `parsertest_$table`" );
620 * Create a dummy uploads directory which will contain a couple
621 * of files in order to pass existence tests.
622 * @return string The directory
624 private function setupUploadDir() {
626 if ( $this->keepUploads ) {
627 $dir = wfTempDir() . '/mwParser-images';
628 if ( is_dir( $dir ) ) {
632 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
635 wfDebug( "Creating upload directory $dir\n" );
637 mkdir( $dir . '/3' );
638 mkdir( $dir . '/3/3a' );
639 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
644 * Restore default values and perform any necessary clean-up
645 * after each test runs.
647 private function teardownGlobals() {
648 RepoGroup::destroySingleton();
649 foreach( $this->savedGlobals as $var => $val ) {
650 $GLOBALS[$var] = $val;
652 if( isset( $this->uploadDir ) ) {
653 $this->teardownUploadDir( $this->uploadDir );
654 unset( $this->uploadDir );
659 * Remove the dummy uploads directory
661 private function teardownUploadDir( $dir ) {
662 if ( $this->keepUploads ) {
666 // delete the files first, then the dirs.
669 "$dir/3/3a/Foobar.jpg",
670 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
671 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
672 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
673 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
683 "$dir/thumb/3/3a/Foobar.jpg",
693 * Delete the specified files, if they exist.
694 * @param array $files full paths to files to delete.
696 private static function deleteFiles( $files ) {
697 foreach( $files as $file ) {
698 if( file_exists( $file ) ) {
705 * Delete the specified directories, if they exist. Must be empty.
706 * @param array $dirs full paths to directories to delete.
708 private static function deleteDirs( $dirs ) {
709 foreach( $dirs as $dir ) {
710 if( is_dir( $dir ) ) {
717 * "Running test $desc..."
719 protected function showTesting( $desc ) {
720 print "Running test $desc... ";
724 * Print a happy success message.
726 * @param string $desc The test name
729 protected function showSuccess( $desc ) {
730 if( $this->showProgress ) {
731 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
737 * Print a failure message and provide some explanatory output
738 * about what went wrong if so configured.
740 * @param string $desc The test name
741 * @param string $result Expected HTML output
742 * @param string $html Actual HTML output
745 protected function showFailure( $desc, $result, $html ) {
746 if( $this->showFailure ) {
747 if( !$this->showProgress ) {
748 # In quiet mode we didn't show the 'Testing' message before the
749 # test, in case it succeeded. Show it now:
750 $this->showTesting( $desc );
752 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
753 if ( $this->showOutput ) {
754 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
756 if( $this->showDiffs ) {
757 print $this->quickDiff( $result, $html );
758 if( !$this->wellFormed( $html ) ) {
759 print "XML error: $this->mXmlError\n";
767 * Run given strings through a diff and return the (colorized) output.
768 * Requires writable /tmp directory and a 'diff' command in the PATH.
770 * @param string $input
771 * @param string $output
772 * @param string $inFileTail Tailing for the input file name
773 * @param string $outFileTail Tailing for the output file name
776 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
777 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
779 $infile = "$prefix-$inFileTail";
780 $this->dumpToFile( $input, $infile );
782 $outfile = "$prefix-$outFileTail";
783 $this->dumpToFile( $output, $outfile );
785 $diff = `diff -au $infile $outfile`;
789 return $this->colorDiff( $diff );
793 * Write the given string to a file, adding a final newline.
795 * @param string $data
796 * @param string $filename
798 private function dumpToFile( $data, $filename ) {
799 $file = fopen( $filename, "wt" );
800 fwrite( $file, $data . "\n" );
805 * Colorize unified diff output if set for ANSI color output.
806 * Subtractions are colored blue, additions red.
808 * @param string $text
811 protected function colorDiff( $text ) {
813 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
814 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
815 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
820 * Show "Reading tests from ..."
822 * @param String $path
824 protected function showRunFile( $path ){
825 print $this->term->color( 1 ) .
826 "Reading tests from \"$path\"..." .
827 $this->term->reset() .
832 * Insert a temporary test article
833 * @param string $name the title, including any prefix
834 * @param string $text the article text
835 * @param int $line the input line number, for reporting errors
837 private function addArticle($name, $text, $line) {
838 $this->setupGlobals();
839 $title = Title::newFromText( $name );
840 if ( is_null($title) ) {
841 wfDie( "invalid title at line $line\n" );
844 $aid = $title->getArticleID( GAID_FOR_UPDATE );
846 wfDie( "duplicate article at line $line\n" );
849 $art = new Article($title);
850 $art->insertNewArticle($text, '', false, false );
851 $this->teardownGlobals();
855 * Steal a callback function from the primary parser, save it for
856 * application to our scary parser. If the hook is not installed,
857 * die a painful dead to warn the others.
858 * @param string $name
860 private function requireHook( $name ) {
862 if( isset( $wgParser->mTagHooks[$name] ) ) {
863 $this->hooks[$name] = $wgParser->mTagHooks[$name];
865 wfDie( "This test suite requires the '$name' hook extension.\n" );
870 * Steal a callback function from the primary parser, save it for
871 * application to our scary parser. If the hook is not installed,
872 * die a painful dead to warn the others.
873 * @param string $name
875 private function requireFunctionHook( $name ) {
877 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
878 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
880 wfDie( "This test suite requires the '$name' function hook extension.\n" );
885 * Run the "tidy" command on text if the $wgUseTidy
888 * @param string $text the text to tidy
892 private function tidy( $text ) {
895 $text = Parser::tidy($text);
900 private function wellFormed( $text ) {
902 Sanitizer::hackDocType() .
907 $parser = xml_parser_create( "UTF-8" );
909 # case folding violates XML standard, turn it off
910 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
912 if( !xml_parse( $parser, $html, true ) ) {
913 $err = xml_error_string( xml_get_error_code( $parser ) );
914 $position = xml_get_current_byte_index( $parser );
915 $fragment = $this->extractFragment( $html, $position );
916 $this->mXmlError = "$err at byte $position:\n$fragment";
917 xml_parser_free( $parser );
920 xml_parser_free( $parser );
924 private function extractFragment( $text, $position ) {
925 $start = max( 0, $position - 10 );
926 $before = $position - $start;
928 $this->term->color( 34 ) .
929 substr( $text, $start, $before ) .
930 $this->term->color( 0 ) .
931 $this->term->color( 31 ) .
932 $this->term->color( 1 ) .
933 substr( $text, $position, 1 ) .
934 $this->term->color( 0 ) .
935 $this->term->color( 34 ) .
936 substr( $text, $position + 1, 9 ) .
937 $this->term->color( 0 ) .
939 $display = str_replace( "\n", ' ', $fragment );
941 str_repeat( ' ', $before ) .
942 $this->term->color( 31 ) .
944 $this->term->color( 0 );
945 return "$display\n$caret";
949 class AnsiTermColorer {
950 function __construct() {
954 * Return ANSI terminal escape code for changing text attribs/color
956 * @param string $color Semicolon-separated list of attribute/color codes
959 public function color( $color ) {
960 global $wgCommandLineDarkBg;
961 $light = $wgCommandLineDarkBg ? "1;" : "0;";
962 return "\x1b[{$light}{$color}m";
966 * Return ANSI terminal escape code for restoring default text attributes
970 public function reset() {
971 return $this->color( 0 );
975 /* A colour-less terminal */
976 class DummyTermColorer {
977 public function color( $color ) {
981 public function reset() {
990 function __construct( $parent ) {
991 $this->parent = $parent;
992 $this->term = $parent->term;
1000 function record( $test, $result ) {
1002 $this->success += ($result ? 1 : 0);
1010 if( $this->total > 0 ) {
1011 $this->reportPercentage( $this->success, $this->total );
1013 wfDie( "No tests found.\n" );
1017 function reportPercentage( $success, $total ) {
1018 $ratio = wfPercent( 100 * $success / $total );
1019 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1020 if( $success == $total ) {
1021 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1023 $failed = $total - $success ;
1024 print $this->term->color( 31 ) . "$failed tests failed!";
1026 print $this->term->reset() . "\n";
1027 return ($success == $total);
1031 class DbTestPreviewer extends TestRecorder {
1032 protected $lb; ///< Database load balancer
1033 protected $db; ///< Database connection to the main DB
1034 protected $curRun; ///< run ID number for the current run
1035 protected $prevRun; ///< run ID number for the previous run, if any
1036 protected $results; ///< Result array
1039 * This should be called before the table prefix is changed
1041 function __construct( $parent ) {
1042 parent::__construct( $parent );
1043 $this->lb = wfGetLBFactory()->newMainLB();
1044 // This connection will have the wiki's table prefix, not parsertest_
1045 $this->db = $this->lb->getConnection( DB_MASTER );
1049 * Set up result recording; insert a record for the run with the date
1050 * and all that fun stuff
1053 global $wgDBtype, $wgDBprefix;
1056 if( ! $this->db->tableExists( 'testrun' )
1057 or ! $this->db->tableExists( 'testitem' ) )
1059 print "WARNING> `testrun` table not found in database.\n";
1060 $this->prevRun = false;
1062 // We'll make comparisons against the previous run later...
1063 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1065 $this->results = array();
1068 function record( $test, $result ) {
1069 parent::record( $test, $result );
1070 $this->results[$test] = $result;
1074 if( $this->prevRun ) {
1075 // f = fail, p = pass, n = nonexistent
1076 // codes show before then after
1078 'fp' => 'previously failing test(s) now PASSING! :)',
1079 'pn' => 'previously PASSING test(s) removed o_O',
1080 'np' => 'new PASSING test(s) :)',
1082 'pf' => 'previously passing test(s) now FAILING! :(',
1083 'fn' => 'previously FAILING test(s) removed O_o',
1084 'nf' => 'new FAILING test(s) :(',
1085 'ff' => 'still FAILING test(s) :(',
1088 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1089 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1090 foreach ( $res as $row ) {
1091 if ( !$this->parent->regex
1092 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1094 $prevResults[$row->ti_name] = $row->ti_success;
1098 $combined = array_keys( $this->results + $prevResults );
1100 # Determine breakdown by change type
1101 $breakdown = array();
1102 foreach ( $combined as $test ) {
1103 if ( !isset( $prevResults[$test] ) ) {
1105 } elseif ( $prevResults[$test] == 1 ) {
1107 } else /* if ( $prevResults[$test] == 0 )*/ {
1110 if ( !isset( $this->results[$test] ) ) {
1112 } elseif ( $this->results[$test] == 1 ) {
1114 } else /*if ( $this->results[$test] == 0 ) */ {
1117 $code = $before . $after;
1118 if ( isset( $table[$code] ) ) {
1119 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1124 foreach ( $table as $code => $label ) {
1125 if( !empty( $breakdown[$code] ) ) {
1126 $count = count($breakdown[$code]);
1127 printf( "\n%4d %s\n", $count, $label );
1128 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1129 print " * $differing_test_name [$statusInfo]\n";
1134 print "No previous test runs to compare against.\n";
1141 ** Returns a string giving information about when a test last had a status change.
1142 ** Could help to track down when regressions were introduced, as distinct from tests
1143 ** which have never passed (which are more change requests than regressions).
1145 private function getTestStatusInfo($testname, $after) {
1147 // If we're looking at a test that has just been removed, then say when it first appeared.
1148 if ( $after == 'n' ) {
1149 $changedRun = $this->db->selectField ( 'testitem',
1151 array( 'ti_name' => $testname ),
1153 $appear = $this->db->selectRow ( 'testrun',
1154 array( 'tr_date', 'tr_mw_version' ),
1155 array( 'tr_id' => $changedRun ),
1157 return "First recorded appearance: "
1158 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1159 . ", " . $appear->tr_mw_version;
1162 // Otherwise, this test has previous recorded results.
1163 // See when this test last had a different result to what we're seeing now.
1165 'ti_name' => $testname,
1166 'ti_success' => ($after == 'f' ? "1" : "0") );
1167 if ( $this->curRun ) {
1168 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1171 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1173 // If no record of ever having had a different result.
1174 if ( is_null ( $changedRun ) ) {
1175 if ($after == "f") {
1176 return "Has never passed";
1178 return "Has never failed";
1182 // Otherwise, we're looking at a test whose status has changed.
1183 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1184 // In this situation, give as much info as we can as to when it changed status.
1185 $pre = $this->db->selectRow ( 'testrun',
1186 array( 'tr_date', 'tr_mw_version' ),
1187 array( 'tr_id' => $changedRun ),
1189 $post = $this->db->selectRow ( 'testrun',
1190 array( 'tr_date', 'tr_mw_version' ),
1191 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1193 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1197 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1201 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1202 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1208 * Commit transaction and clean up for result recording
1211 $this->lb->commitMasterChanges();
1212 $this->lb->closeAll();
1218 class DbTestRecorder extends DbTestPreviewer {
1220 * Set up result recording; insert a record for the run with the date
1221 * and all that fun stuff
1224 global $wgDBtype, $wgDBprefix;
1227 if( ! $this->db->tableExists( 'testrun' )
1228 or ! $this->db->tableExists( 'testitem' ) )
1230 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1231 if ($wgDBtype === 'postgres')
1232 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1234 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1235 echo "OK, resuming.\n";
1240 $this->db->insert( 'testrun',
1242 'tr_date' => $this->db->timestamp(),
1243 'tr_mw_version' => SpecialVersion::getVersion(),
1244 'tr_php_version' => phpversion(),
1245 'tr_db_version' => $this->db->getServerVersion(),
1246 'tr_uname' => php_uname()
1249 if ($wgDBtype === 'postgres')
1250 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1252 $this->curRun = $this->db->insertId();
1256 * Record an individual test item's success or failure to the db
1257 * @param string $test
1258 * @param bool $result
1260 function record( $test, $result ) {
1261 parent::record( $test, $result );
1262 $this->db->insert( 'testitem',
1264 'ti_run' => $this->curRun,
1266 'ti_success' => $result ? 1 : 0,