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