Fix bug 11771: Signup form now not shown if in read-only mode.
[mediawiki.git] / maintenance / parserTests.inc
blob1e1c483a0b90bdfbdc9853162f4fe021a3b5673c
1 <?php
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
20 /**
21  * @todo Make this more independent of the configuration (and if possible the database)
22  * @todo document
23  * @file
24  * @ingroup Maintenance
25  */
27 /** */
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" );
36 /**
37  * @ingroup Maintenance
38  */
39 class ParserTest {
40         /**
41          * boolean $color whereas output should be colorized
42          */
43         private $color;
45         /**
46          * boolean $showOutput Show test output
47          */
48         private $showOutput;
50         /**
51          * Sets terminal colorization and diff/quick modes depending on OS and
52          * command-line options (--color and --quick).
53          */
54         public function ParserTest() {
55                 global $options;
57                 # Only colorize output if stdout is a terminal.
58                 $this->color = !wfIsWindows() && posix_isatty(1);
60                 if( isset( $options['color'] ) ) {
61                         switch( $options['color'] ) {
62                         case 'no':
63                                 $this->color = false;
64                                 break;
65                         case 'yes':
66                         default:
67                                 $this->color = true;
68                                 break;
69                         }
70                 }
71                 $this->term = $this->color
72                         ? new AnsiTermColorer()
73                         : new DummyTermColorer();
75                 $this->showDiffs = !isset( $options['quick'] );
76                 $this->showProgress = !isset( $options['quiet'] );
77                 $this->showFailure = !(
78                         isset( $options['quiet'] )
79                         && ( isset( $options['record'] )
80                                 || isset( $options['compare'] ) ) ); // redundant output
81                 
82                 $this->showOutput = isset( $options['show-output'] );
85                 if (isset($options['regex'])) {
86                         $this->regex = $options['regex'];
87                 } else {
88                         # Matches anything
89                         $this->regex = '';
90                 }
92                 if( isset( $options['record'] ) ) {
93                         $this->recorder = new DbTestRecorder( $this->term );
94                 } elseif( isset( $options['compare'] ) ) {
95                         $this->recorder = new DbTestPreviewer( $this->term );
96                 } else {
97                         $this->recorder = new TestRecorder( $this->term );
98                 }
99                 $this->keepUploads = isset( $options['keep-uploads'] );
101                 $this->hooks = array();
102                 $this->functionHooks = array();
103         }
105         /**
106          * Remove last character if it is a newline
107          */
108         private function chomp($s) {
109                 if (substr($s, -1) === "\n") {
110                         return substr($s, 0, -1);
111                 }
112                 else {
113                         return $s;
114                 }
115         }
117         /**
118          * Run a series of tests listed in the given text files.
119          * Each test consists of a brief description, wikitext input,
120          * and the expected HTML output.
121          *
122          * Prints status updates on stdout and counts up the total
123          * number and percentage of passed tests.
124          *
125          * @param array of strings $filenames
126          * @return bool True if passed all tests, false if any tests failed.
127          */
128         public function runTestsFromFiles( $filenames ) {
129                 $this->recorder->start();
130                 $ok = true;
131                 foreach( $filenames as $filename ) {
132                         $ok = $this->runFile( $filename ) && $ok;
133                 }
134                 $this->recorder->report();
135                 $this->recorder->end();
136                 return $ok;
137         }
139         private function runFile( $filename ) {
140                 $infile = fopen( $filename, 'rt' );
141                 if( !$infile ) {
142                         wfDie( "Couldn't open $filename\n" );
143                 } else {
144                         global $IP;
145                         $relative = wfRelativePath( $filename, $IP );
146                         $this->showRunFile( $relative );
147                 }
149                 $data = array();
150                 $section = null;
151                 $n = 0;
152                 $ok = true;
153                 while( false !== ($line = fgets( $infile ) ) ) {
154                         $n++;
155                         $matches = array();
156                         if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
157                                 $section = strtolower( $matches[1] );
158                                 if( $section == 'endarticle') {
159                                         if( !isset( $data['text'] ) ) {
160                                                 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
161                                         }
162                                         if( !isset( $data['article'] ) ) {
163                                                 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
164                                         }
165                                         $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
166                                         $data = array();
167                                         $section = null;
168                                         continue;
169                                 }
170                                 if( $section == 'endhooks' ) {
171                                         if( !isset( $data['hooks'] ) ) {
172                                                 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
173                                         }
174                                         foreach( explode( "\n", $data['hooks'] ) as $line ) {
175                                                 $line = trim( $line );
176                                                 if( $line ) {
177                                                         $this->requireHook( $line );
178                                                 }
179                                         }
180                                         $data = array();
181                                         $section = null;
182                                         continue;
183                                 }
184                                 if( $section == 'endfunctionhooks' ) {
185                                         if( !isset( $data['functionhooks'] ) ) {
186                                                 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
187                                         }
188                                         foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
189                                                 $line = trim( $line );
190                                                 if( $line ) {
191                                                         $this->requireFunctionHook( $line );
192                                                 }
193                                         }
194                                         $data = array();
195                                         $section = null;
196                                         continue;
197                                 }
198                                 if( $section == 'end' ) {
199                                         if( !isset( $data['test'] ) ) {
200                                                 wfDie( "'end' without 'test' at line $n of $filename\n" );
201                                         }
202                                         if( !isset( $data['input'] ) ) {
203                                                 wfDie( "'end' without 'input' at line $n of $filename\n" );
204                                         }
205                                         if( !isset( $data['result'] ) ) {
206                                                 wfDie( "'end' without 'result' at line $n of $filename\n" );
207                                         }
208                                         if( !isset( $data['options'] ) ) {
209                                                 $data['options'] = '';
210                                         }
211                                         else {
212                                                 $data['options'] = $this->chomp( $data['options'] );
213                                         }
214                                         if (preg_match('/\\bdisabled\\b/i', $data['options'])
215                                                 || !preg_match("/{$this->regex}/i", $data['test'])) {
216                                                 # disabled test
217                                                 $data = array();
218                                                 $section = null;
219                                                 continue;
220                                         }
221                                         $result = $this->runTest(
222                                                 $this->chomp( $data['test'] ),
223                                                 $this->chomp( $data['input'] ),
224                                                 $this->chomp( $data['result'] ),
225                                                 $this->chomp( $data['options'] ) );
226                                         $ok = $ok && $result;
227                                         $this->recorder->record( $this->chomp( $data['test'] ), $result );
228                                         $data = array();
229                                         $section = null;
230                                         continue;
231                                 }
232                                 if ( isset ($data[$section] ) ) {
233                                         wfDie( "duplicate section '$section' at line $n of $filename\n" );
234                                 }
235                                 $data[$section] = '';
236                                 continue;
237                         }
238                         if( $section ) {
239                                 $data[$section] .= $line;
240                         }
241                 }
242                 if ( $this->showProgress ) {
243                         print "\n";
244                 }
245                 return $ok;
246         }
248         /**
249          * Run a given wikitext input through a freshly-constructed wiki parser,
250          * and compare the output against the expected results.
251          * Prints status and explanatory messages to stdout.
252          *
253          * @param string $input Wikitext to try rendering
254          * @param string $result Result to output
255          * @return bool
256          */
257         private function runTest( $desc, $input, $result, $opts ) {
258                 global $wgParserConf;
259                 if( $this->showProgress ) {
260                         $this->showTesting( $desc );
261                 }
263                 $this->setupGlobals($opts);
265                 $user = new User();
266                 $options = ParserOptions::newFromUser( $user );
268                 if (preg_match('/\\bmath\\b/i', $opts)) {
269                         # XXX this should probably be done by the ParserOptions
270                         $options->setUseTex(true);
271                 }
273                 $m = array();
274                 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
275                         $titleText = $m[1];
276                 }
277                 else {
278                         $titleText = 'Parser test';
279                 }
281                 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
283                 $class = $wgParserConf['class'];
284                 $parser = new $class( $wgParserConf );
285                 foreach( $this->hooks as $tag => $callback ) {
286                         $parser->setHook( $tag, $callback );
287                 }
288                 foreach( $this->functionHooks as $tag => $bits ) {
289                         list( $callback, $flags ) = $bits;
290                         $parser->setFunctionHook( $tag, $callback, $flags );
291                 }
292                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
294                 $title =& Title::makeTitle( NS_MAIN, $titleText );
296                 $matches = array();
297                 if (preg_match('/\\bpst\\b/i', $opts)) {
298                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
299                 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
300                         $out = $parser->transformMsg( $input, $options );
301                 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
302                         $section = $matches[1];
303                         $out = $parser->getSection( $input, $section );
304                 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
305                         $section = $matches[1];
306                         $replace = $matches[2];
307                         $out = $parser->replaceSection( $input, $section, $replace );
308                 } else {
309                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
310                         $out = $output->getText();
312                         if (preg_match('/\\bill\\b/i', $opts)) {
313                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
314                         } else if (preg_match('/\\bcat\\b/i', $opts)) {
315                                 global $wgOut;
316                                 $wgOut->addCategoryLinks($output->getCategories());
317                                 $cats = $wgOut->getCategoryLinks();
318                                 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
319                         }
321                         $result = $this->tidy($result);
322                 }
324                 $this->teardownGlobals();
326                 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
327                         return $this->showSuccess( $desc );
328                 } else {
329                         return $this->showFailure( $desc, $result, $out );
330                 }
331         }
334         /**
335          * Use a regex to find out the value of an option
336          * @param $regex A regex, the first group will be the value returned
337          * @param $opts Options line to look in
338          * @param $defaults Default value returned if the regex does not match
339          */
340         private static function getOptionValue( $regex, $opts, $default ) {
341                 $m = array();
342                 if( preg_match( $regex, $opts, $m ) ) {
343                         return $m[1];
344                 } else {
345                         return $default;
346                 }
347         }
349         /**
350          * Set up the global variables for a consistent environment for each test.
351          * Ideally this should replace the global configuration entirely.
352          */
353         private function setupGlobals($opts = '') {
354                 # Save the prefixed / quoted table names for later use when we make the temporaries.
355                 $db = wfGetDB( DB_SLAVE );
356                 $this->oldTableNames = array();
357                 foreach( $this->listTables() as $table ) {
358                         $this->oldTableNames[$table] = $db->tableName( $table );
359                 }
360                 if( !isset( $this->uploadDir ) ) {
361                         $this->uploadDir = $this->setupUploadDir();
362                 }
364                 # Find out values for some special options.
365                 $lang =
366                         self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
367                 $variant =
368                         self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
369                 $maxtoclevel =
370                         self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
372                 $settings = array(
373                         'wgServer' => 'http://localhost',
374                         'wgScript' => '/index.php',
375                         'wgScriptPath' => '/',
376                         'wgArticlePath' => '/wiki/$1',
377                         'wgActionPaths' => array(),
378                         'wgLocalFileRepo' => array(
379                                 'class' => 'LocalRepo',
380                                 'name' => 'local',
381                                 'directory' => $this->uploadDir,
382                                 'url' => 'http://example.com/images',
383                                 'hashLevels' => 2,
384                                 'transformVia404' => false,
385                         ),
386                         'wgEnableUploads' => true,
387                         'wgStyleSheetPath' => '/skins',
388                         'wgSitename' => 'MediaWiki',
389                         'wgServerName' => 'Britney Spears',
390                         'wgLanguageCode' => $lang,
391                         'wgContLanguageCode' => $lang,
392                         'wgDBprefix' => 'parsertest_',
393                         'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
394                         'wgLang' => null,
395                         'wgContLang' => null,
396                         'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
397                         'wgMaxTocLevel' => $maxtoclevel,
398                         'wgCapitalLinks' => true,
399                         'wgNoFollowLinks' => true,
400                         'wgThumbnailScriptPath' => false,
401                         'wgUseTeX' => false,
402                         'wgLocaltimezone' => 'UTC',
403                         'wgAllowExternalImages' => true,
404                         'wgUseTidy' => false,
405                         'wgDefaultLanguageVariant' => $variant,
406                         'wgVariantArticlePath' => false,
407                         'wgGroupPermissions' => array( '*' => array(
408                                 'createaccount' => true,
409                                 'read'          => true,
410                                 'edit'          => true,
411                                 'createpage'    => true,
412                                 'createtalk'    => true,
413                         ) ),
414                         'wgDefaultExternalStore' => array(),
415                         'wgForeignFileRepos' => array(),
416                         );
417                 $this->savedGlobals = array();
418                 foreach( $settings as $var => $val ) {
419                         $this->savedGlobals[$var] = $GLOBALS[$var];
420                         $GLOBALS[$var] = $val;
421                 }
422                 $langObj = Language::factory( $lang );
423                 $GLOBALS['wgLang'] = $langObj;
424                 $GLOBALS['wgContLang'] = $langObj;
426                 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
427                 $this->setupDatabase();
429                 global $wgUser;
430                 $wgUser = new User();
431         }
433         /**
434          * List of temporary tables to create, without prefix.
435          * Some of these probably aren't necessary.
436          */
437         private function listTables() {
438                 global $wgDBtype;
439                 $tables = array('user', 'page', 'page_restrictions',
440                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
441                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
442                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
443                         'recentchanges', 'watchlist', 'math', 'interwiki',
444                         'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
445                         'archive', 'user_groups', 'page_props', 'category'
446                 );
448                 if ($wgDBtype === 'mysql') 
449                         array_push( $tables, 'searchindex' );
450                 
451                 // Allow extensions to add to the list of tables to duplicate;
452                 // may be necessary if they hook into page save or other code
453                 // which will require them while running tests.
454                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
456                 return $tables;
457         }
459         /**
460          * Set up a temporary set of wiki tables to work with for the tests.
461          * Currently this will only be done once per run, and any changes to
462          * the db will be visible to later tests in the run.
463          */
464         private function setupDatabase() {
465                 static $setupDB = false;
466                 global $wgDBprefix;
468                 # Make sure we don't mess with the live DB
469                 if (!$setupDB && $wgDBprefix === 'parsertest_') {
470                         # oh teh horror
471                         LBFactory::destroy();
472                         $db = wfGetDB( DB_MASTER );
474                         $tables = $this->listTables();
476                         if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
477                                 # Database that supports CREATE TABLE ... LIKE
478                                 global $wgDBtype;
479                                 if( $wgDBtype == 'postgres' ) {
480                                         $def = 'INCLUDING DEFAULTS';
481                                 } else {
482                                         $def = '';
483                                 }
484                                 foreach ($tables as $tbl) {
485                                         $newTableName = $db->tableName( $tbl );
486                                         $tableName = $this->oldTableNames[$tbl];
487                                         $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
488                                 }
489                         } else {
490                                 # Hack for MySQL versions < 4.1, which don't support
491                                 # "CREATE TABLE ... LIKE". Note that
492                                 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
493                                 # would not create the indexes we need....
494                                 foreach ($tables as $tbl) {
495                                         $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
496                                         $row = $db->fetchRow($res);
497                                         $create = $row[1];
498                                         $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
499                                                 . $wgDBprefix . $tbl .'`', $create);
500                                         if ($create === $create_tmp) {
501                                                 # Couldn't do replacement
502                                                 wfDie("could not create temporary table $tbl");
503                                         }
504                                         $db->query($create_tmp);
505                                 }
507                         }
509                         # Hack: insert a few Wikipedia in-project interwiki prefixes,
510                         # for testing inter-language links
511                         $db->insert( 'interwiki', array(
512                                 array( 'iw_prefix' => 'Wikipedia',
513                                        'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
514                                        'iw_local'  => 0 ),
515                                 array( 'iw_prefix' => 'MeatBall',
516                                        'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
517                                        'iw_local'  => 0 ),
518                                 array( 'iw_prefix' => 'zh',
519                                        'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
520                                        'iw_local'  => 1 ),
521                                 array( 'iw_prefix' => 'es',
522                                        'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
523                                        'iw_local'  => 1 ),
524                                 array( 'iw_prefix' => 'fr',
525                                        'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
526                                        'iw_local'  => 1 ),
527                                 array( 'iw_prefix' => 'ru',
528                                        'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
529                                        'iw_local'  => 1 ),
530                                 ) );
532                         # Hack: Insert an image to work with
533                         $db->insert( 'image', array(
534                                 'img_name'        => 'Foobar.jpg',
535                                 'img_size'        => 12345,
536                                 'img_description' => 'Some lame file',
537                                 'img_user'        => 1,
538                                 'img_user_text'   => 'WikiSysop',
539                                 'img_timestamp'   => $db->timestamp( '20010115123500' ),
540                                 'img_width'       => 1941,
541                                 'img_height'      => 220,
542                                 'img_bits'        => 24,
543                                 'img_media_type'  => MEDIATYPE_BITMAP,
544                                 'img_major_mime'  => "image",
545                                 'img_minor_mime'  => "jpeg",
546                                 'img_metadata'    => serialize( array() ),
547                                 ) );
549                         # Update certain things in site_stats
550                         $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
552                         $setupDB = true;
553                 }
554         }
556         /**
557          * Create a dummy uploads directory which will contain a couple
558          * of files in order to pass existence tests.
559          * @return string The directory
560          */
561         private function setupUploadDir() {
562                 global $IP;
563                 if ( $this->keepUploads ) {
564                         $dir = wfTempDir() . '/mwParser-images';
565                         if ( is_dir( $dir ) ) {
566                                 return $dir;
567                         }
568                 } else {
569                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
570                 }
572                 wfDebug( "Creating upload directory $dir\n" );
573                 mkdir( $dir );
574                 mkdir( $dir . '/3' );
575                 mkdir( $dir . '/3/3a' );
576                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
577                 return $dir;
578         }
580         /**
581          * Restore default values and perform any necessary clean-up
582          * after each test runs.
583          */
584         private function teardownGlobals() {
585                 RepoGroup::destroySingleton();
586                 foreach( $this->savedGlobals as $var => $val ) {
587                         $GLOBALS[$var] = $val;
588                 }
589                 if( isset( $this->uploadDir ) ) {
590                         $this->teardownUploadDir( $this->uploadDir );
591                         unset( $this->uploadDir );
592                 }
593         }
595         /**
596          * Remove the dummy uploads directory
597          */
598         private function teardownUploadDir( $dir ) {
599                 if ( $this->keepUploads ) {
600                         return;
601                 }
603                 // delete the files first, then the dirs.
604                 self::deleteFiles(
605                         array (
606                                 "$dir/3/3a/Foobar.jpg",
607                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
608                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
609                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
610                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
611                         )
612                 );
614                 self::deleteDirs(
615                         array (
616                                 "$dir/3/3a",
617                                 "$dir/3",
618                                 "$dir/thumb/6/65",
619                                 "$dir/thumb/6",
620                                 "$dir/thumb/3/3a/Foobar.jpg",
621                                 "$dir/thumb/3/3a",
622                                 "$dir/thumb/3",
623                                 "$dir/thumb",
624                                 "$dir",
625                         )
626                 );
627         }
629         /**
630          * Delete the specified files, if they exist.
631          * @param array $files full paths to files to delete.
632          */
633         private static function deleteFiles( $files ) {
634                 foreach( $files as $file ) {
635                         if( file_exists( $file ) ) {
636                                 unlink( $file );
637                         }
638                 }
639         }
641         /**
642          * Delete the specified directories, if they exist. Must be empty.
643          * @param array $dirs full paths to directories to delete.
644          */
645         private static function deleteDirs( $dirs ) {
646                 foreach( $dirs as $dir ) {
647                         if( is_dir( $dir ) ) {
648                                 rmdir( $dir );
649                         }
650                 }
651         }
653         /**
654          * "Running test $desc..."
655          */
656         protected function showTesting( $desc ) {
657                 print "Running test $desc... ";
658         }
660         /**
661          * Print a happy success message.
662          *
663          * @param string $desc The test name
664          * @return bool
665          */
666         protected function showSuccess( $desc ) {
667                 if( $this->showProgress ) {
668                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
669                 }
670                 return true;
671         }
673         /**
674          * Print a failure message and provide some explanatory output
675          * about what went wrong if so configured.
676          *
677          * @param string $desc The test name
678          * @param string $result Expected HTML output
679          * @param string $html Actual HTML output
680          * @return bool
681          */
682         protected function showFailure( $desc, $result, $html ) {
683                 if( $this->showFailure ) {
684                         if( !$this->showProgress ) {
685                                 # In quiet mode we didn't show the 'Testing' message before the
686                                 # test, in case it succeeded. Show it now:
687                                 $this->showTesting( $desc );
688                         }
689                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
690                         if ( $this->showOutput ) {
691                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
692                         }
693                         if( $this->showDiffs ) {
694                                 print $this->quickDiff( $result, $html );
695                                 if( !$this->wellFormed( $html ) ) {
696                                         print "XML error: $this->mXmlError\n";
697                                 }
698                         }
699                 }
700                 return false;
701         }
703         /**
704          * Run given strings through a diff and return the (colorized) output.
705          * Requires writable /tmp directory and a 'diff' command in the PATH.
706          *
707          * @param string $input
708          * @param string $output
709          * @param string $inFileTail Tailing for the input file name
710          * @param string $outFileTail Tailing for the output file name
711          * @return string
712          */
713         protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
714                 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
716                 $infile = "$prefix-$inFileTail";
717                 $this->dumpToFile( $input, $infile );
719                 $outfile = "$prefix-$outFileTail";
720                 $this->dumpToFile( $output, $outfile );
722                 $diff = `diff -au $infile $outfile`;
723                 unlink( $infile );
724                 unlink( $outfile );
726                 return $this->colorDiff( $diff );
727         }
729         /**
730          * Write the given string to a file, adding a final newline.
731          *
732          * @param string $data
733          * @param string $filename
734          */
735         private function dumpToFile( $data, $filename ) {
736                 $file = fopen( $filename, "wt" );
737                 fwrite( $file, $data . "\n" );
738                 fclose( $file );
739         }
741         /**
742          * Colorize unified diff output if set for ANSI color output.
743          * Subtractions are colored blue, additions red.
744          *
745          * @param string $text
746          * @return string
747          */
748         protected function colorDiff( $text ) {
749                 return preg_replace(
750                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
751                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
752                                $this->term->color( 31 ) . '$1' . $this->term->reset() ),
753                         $text );
754         }
756         /**
757          * Show "Reading tests from ..."
758          *
759          * @param String $path
760          */
761         protected function showRunFile( $path ){
762                 print $this->term->color( 1 ) .
763                         "Reading tests from \"$path\"..." .
764                         $this->term->reset() .
765                         "\n";
766         }
768         /**
769          * Insert a temporary test article
770          * @param string $name the title, including any prefix
771          * @param string $text the article text
772          * @param int $line the input line number, for reporting errors
773          */
774         private function addArticle($name, $text, $line) {
775                 $this->setupGlobals();
776                 $title = Title::newFromText( $name );
777                 if ( is_null($title) ) {
778                         wfDie( "invalid title at line $line\n" );
779                 }
781                 $aid = $title->getArticleID( GAID_FOR_UPDATE );
782                 if ($aid != 0) {
783                         wfDie( "duplicate article at line $line\n" );
784                 }
786                 $art = new Article($title);
787                 $art->insertNewArticle($text, '', false, false );
788                 $this->teardownGlobals();
789         }
791         /**
792          * Steal a callback function from the primary parser, save it for
793          * application to our scary parser. If the hook is not installed,
794          * die a painful dead to warn the others.
795          * @param string $name
796          */
797         private function requireHook( $name ) {
798                 global $wgParser;
799                 if( isset( $wgParser->mTagHooks[$name] ) ) {
800                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
801                 } else {
802                         wfDie( "This test suite requires the '$name' hook extension.\n" );
803                 }
804         }
806         /**
807          * Steal a callback function from the primary parser, save it for
808          * application to our scary parser. If the hook is not installed,
809          * die a painful dead to warn the others.
810          * @param string $name
811          */
812         private function requireFunctionHook( $name ) {
813                 global $wgParser;
814                 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
815                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
816                 } else {
817                         wfDie( "This test suite requires the '$name' function hook extension.\n" );
818                 }
819         }
821         /*
822          * Run the "tidy" command on text if the $wgUseTidy
823          * global is true
824          *
825          * @param string $text the text to tidy
826          * @return string
827          * @static
828          */
829         private function tidy( $text ) {
830                 global $wgUseTidy;
831                 if ($wgUseTidy) {
832                         $text = Parser::tidy($text);
833                 }
834                 return $text;
835         }
837         private function wellFormed( $text ) {
838                 $html =
839                         Sanitizer::hackDocType() .
840                         '<html>' .
841                         $text .
842                         '</html>';
844                 $parser = xml_parser_create( "UTF-8" );
846                 # case folding violates XML standard, turn it off
847                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
849                 if( !xml_parse( $parser, $html, true ) ) {
850                         $err = xml_error_string( xml_get_error_code( $parser ) );
851                         $position = xml_get_current_byte_index( $parser );
852                         $fragment = $this->extractFragment( $html, $position );
853                         $this->mXmlError = "$err at byte $position:\n$fragment";
854                         xml_parser_free( $parser );
855                         return false;
856                 }
857                 xml_parser_free( $parser );
858                 return true;
859         }
861         private function extractFragment( $text, $position ) {
862                 $start = max( 0, $position - 10 );
863                 $before = $position - $start;
864                 $fragment = '...' .
865                         $this->term->color( 34 ) .
866                         substr( $text, $start, $before ) .
867                         $this->term->color( 0 ) .
868                         $this->term->color( 31 ) .
869                         $this->term->color( 1 ) .
870                         substr( $text, $position, 1 ) .
871                         $this->term->color( 0 ) .
872                         $this->term->color( 34 ) .
873                         substr( $text, $position + 1, 9 ) .
874                         $this->term->color( 0 ) .
875                         '...';
876                 $display = str_replace( "\n", ' ', $fragment );
877                 $caret = '   ' .
878                         str_repeat( ' ', $before ) .
879                         $this->term->color( 31 ) .
880                         '^' .
881                         $this->term->color( 0 );
882                 return "$display\n$caret";
883         }
886 class AnsiTermColorer {
887         function __construct() {
888         }
890         /**
891          * Return ANSI terminal escape code for changing text attribs/color
892          *
893          * @param string $color Semicolon-separated list of attribute/color codes
894          * @return string
895          */
896         public function color( $color ) {
897                 global $wgCommandLineDarkBg;
898                 $light = $wgCommandLineDarkBg ? "1;" : "0;";
899                 return "\x1b[{$light}{$color}m";
900         }
902         /**
903          * Return ANSI terminal escape code for restoring default text attributes
904          *
905          * @return string
906          */
907         public function reset() {
908                 return $this->color( 0 );
909         }
912 /* A colour-less terminal */
913 class DummyTermColorer {
914         public function color( $color ) {
915                 return '';
916         }
918         public function reset() {
919                 return '';
920         }
923 class TestRecorder {
924         function __construct( $term ) {
925                 $this->term = $term;
926         }
928         function start() {
929                 $this->total = 0;
930                 $this->success = 0;
931         }
933         function record( $test, $result ) {
934                 $this->total++;
935                 $this->success += ($result ? 1 : 0);
936         }
938         function end() {
939                 // dummy
940         }
942         function report() {
943                 if( $this->total > 0 ) {
944                         $this->reportPercentage( $this->success, $this->total );
945                 } else {
946                         wfDie( "No tests found.\n" );
947                 }
948         }
950         function reportPercentage( $success, $total ) {
951                 $ratio = wfPercent( 100 * $success / $total );
952                 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
953                 if( $success == $total ) {
954                         print $this->term->color( 32 ) . "ALL TESTS PASSED!";
955                 } else {
956                         $failed = $total - $success ;
957                         print $this->term->color( 31 ) . "$failed tests failed!";
958                 }
959                 print $this->term->reset() . "\n";
960                 return ($success == $total);
961         }
964 class DbTestRecorder extends TestRecorder  {
965         protected $db;      ///< Database connection to the main DB
966         protected $curRun;  ///< run ID number for the current run
967         protected $prevRun; ///< run ID number for the previous run, if any
969         function __construct( $term ) {
970                 parent::__construct( $term );
971                 $this->db = wfGetDB( DB_MASTER );
972         }
974         /**
975          * Set up result recording; insert a record for the run with the date
976          * and all that fun stuff
977          */
978         function start() {
979                 global $wgDBtype;
980                 parent::start();
982                 $this->db->begin();
984                 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
985                         print "WARNING> `testrun` table not found in database. Trying to create table.\n";
986             if ($wgDBtype === 'postgres')
987                                 dbsource( dirname(__FILE__) . '/testRunner.postgres.sql',  $this->db );
988                         else
989                                 dbsource( dirname(__FILE__) . '/testRunner.sql',  $this->db );
990                         echo "OK, resuming.\n";
991                 }
993                 // We'll make comparisons against the previous run later...
994                 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
996                 $this->db->insert( 'testrun',
997                         array(
998                                 'tr_date'        => $this->db->timestamp(),
999                                 'tr_mw_version'  => SpecialVersion::getVersion(),
1000                                 'tr_php_version' => phpversion(),
1001                                 'tr_db_version'  => $this->db->getServerVersion(),
1002                                 'tr_uname'       => php_uname()
1003                         ),
1004                         __METHOD__ );
1005                         if ($wgDBtype === 'postgres')
1006                                 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1007                         else
1008                                 $this->curRun = $this->db->insertId();
1009         }
1011         /**
1012          * Record an individual test item's success or failure to the db
1013          * @param string $test
1014          * @param bool $result
1015          */
1016         function record( $test, $result ) {
1017                 parent::record( $test, $result );
1018                 $this->db->insert( 'testitem',
1019                         array(
1020                                 'ti_run'     => $this->curRun,
1021                                 'ti_name'    => $test,
1022                                 'ti_success' => $result ? 1 : 0,
1023                         ),
1024                         __METHOD__ );
1025         }
1027         /**
1028          * Commit transaction and clean up for result recording
1029          */
1030         function end() {
1031                 $this->db->commit();
1032                 parent::end();
1033         }
1035         function report() {
1036                 if( $this->prevRun ) {
1037                         $table = array(
1038                                 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1039                                 array( 'previously PASSING test(s) removed o_O', 1, null ),
1040                                 array( 'new PASSING test(s) :)', null, 1 ),
1042                                 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1043                                 array( 'previously FAILING test(s) removed O_o', 0, null ),
1044                                 array( 'new FAILING test(s) :(', null, 0 ),
1045                                 array( 'still FAILING test(s) :(', 0, 0 ),
1046                         );
1047                         foreach( $table as $criteria ) {
1048                                 list( $label, $before, $after ) = $criteria;
1049                                 $differences = $this->compareResult( $before, $after );
1050                                 if( $differences ) {
1051                                         $count = count($differences);
1052                                         printf( "\n%4d %s\n", $count, $label );
1053                                         foreach ($differences as $differing_test_name => $statusInfo) {
1054                                                 print "      * $differing_test_name  [$statusInfo]\n";
1055                                         }
1056                                 }
1057                         }
1058                 } else {
1059                         print "No previous test runs to compare against.\n";
1060                 }
1061                 print "\n";
1062                 parent::report();
1063         }
1065         /**
1066          ** Returns an array of the test names with changed results, based on the specified
1067          ** before/after criteria.
1068          */
1069         private function compareResult( $before, $after ) {
1070                 $testitem = $this->db->tableName( 'testitem' );
1071                 $prevRun = intval( $this->prevRun );
1072                 $curRun = intval( $this->curRun );
1073                 $prevStatus = $this->condition( $before );
1074                 $curStatus = $this->condition( $after );
1076                 // note: requires mysql >= ver 4.1 for subselects
1077                 if( is_null( $after ) ) {
1078                         $sql = "
1079                                 select prev.ti_name as t from $testitem as prev
1080                                         where prev.ti_run=$prevRun and
1081                                                 prev.ti_success $prevStatus and
1082                                                 (select current.ti_success from $testitem as current
1083                                                         where current.ti_run=$curRun
1084                                                                 and prev.ti_name=current.ti_name) $curStatus";
1085                 } else {
1086                         $sql = "
1087                                 select current.ti_name as t from $testitem as current 
1088                                         where current.ti_run=$curRun and
1089                                                 current.ti_success $curStatus and
1090                                                 (select prev.ti_success from $testitem as prev
1091                                                         where prev.ti_run=$prevRun
1092                                                                 and prev.ti_name=current.ti_name) $prevStatus";
1093                 }
1094                 $result = $this->db->query( $sql, __METHOD__ );
1095                 $retval = array();
1096                 while ($row = $this->db->fetchObject( $result )) {
1097                         $testname = $row->t;
1098                         $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1099                 }
1100                 $this->db->freeResult( $result );
1101                 return $retval;
1102         }
1104         /**
1105          ** Returns a string giving information about when a test last had a status change.
1106          ** Could help to track down when regressions were introduced, as distinct from tests
1107          ** which have never passed (which are more change requests than regressions).
1108          */
1109         private function getTestStatusInfo($testname, $after, $curRun) {
1111                 // If we're looking at a test that has just been removed, then say when it first appeared.
1112                 if ( is_null( $after ) ) {
1113                         $changedRun = $this->db->selectField ( 'testitem',
1114                                                                                                    'MIN(ti_run)',
1115                                                                                                    array( 'ti_name' => $testname ),
1116                                                                                                    __METHOD__ );
1117                         $appear = $this->db->selectRow ( 'testrun',
1118                                                                                          array( 'tr_date', 'tr_mw_version' ),
1119                                                                                          array( 'tr_id' => $changedRun ),
1120                                                                                          __METHOD__ );
1121                         return "First recorded appearance: "
1122                                . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
1123                                .  ", " . $appear->tr_mw_version;
1124                 }
1126                 // Otherwise, this test has previous recorded results.
1127                 // See when this test last had a different result to what we're seeing now.
1128                 $changedRun = $this->db->selectField ( 'testitem',
1129                                                                                            'MAX(ti_run)',
1130                                                                                            array( 
1131                                                                                                'ti_name'    => $testname,
1132                                                                                                'ti_success' => ($after ? "0" : "1"),
1133                                                                                                "ti_run != " . $this->db->addQuotes ( $curRun )
1134                                                                                                 ), 
1135                                                                                                 __METHOD__ );
1137                 // If no record of ever having had a different result.
1138                 if ( is_null ( $changedRun ) ) {
1139                         if ($after == "0") {
1140                                 return "Has never passed";
1141                         } else {
1142                                 return "Has never failed";
1143                         }
1144                 }
1146                 // Otherwise, we're looking at a test whose status has changed.
1147                 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1148                 // In this situation, give as much info as we can as to when it changed status.
1149                 $pre  = $this->db->selectRow ( 'testrun',
1150                                                                                 array( 'tr_date', 'tr_mw_version' ),
1151                                                                                 array( 'tr_id' => $changedRun ),
1152                                                                                 __METHOD__ );
1153                 $post = $this->db->selectRow ( 'testrun',
1154                                                                                 array( 'tr_date', 'tr_mw_version' ),
1155                                                                                 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1156                                                                                 __METHOD__,
1157                                                                                 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1158                                                                          );
1160                 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1161                                 . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
1162                                 . " and "
1163                                 . date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) .  ", " . $post->tr_mw_version ;
1164         }
1166         /**
1167          ** Helper function for compareResult() database querying.
1168          */
1169         private function condition( $value ) {
1170                 if( is_null( $value ) ) {
1171                         return 'IS NULL';
1172                 } else {
1173                         return '=' . intval( $value );
1174                 }
1175         }
1179 class DbTestPreviewer extends DbTestRecorder  {
1180         /**
1181          * Commit transaction and clean up for result recording
1182          */
1183         function end() {
1184                 $this->db->rollback();
1185                 TestRecorder::end();
1186         }