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