Localisation updates Cantonese, Chinese and Old/Late Time Chinese
[mediawiki.git] / maintenance / parserTests.inc
blobba8349737bb7367892b4e3958130758824f65986
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
20 /**
21  * @todo Make this more independent of the configuration (and if possible the database)
22  * @todo document
23  * @file
24  * @ingroup Maintenance
25  */
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
36 /**
37  * @ingroup Maintenance
38  */
39 class ParserTest {
40         /**
41          * boolean $color whereas output should be colorized
42          */
43         private $color;
45         /**
46          * boolean $showOutput Show test output
47          */
48         private $showOutput;
50         /**
51          * boolean $useTemporaryTables Use temporary tables for the temporary database
52          */
53         private $useTemporaryTables = true;
55         /**
56          * boolean $databaseSetupDone True if the database has been set up
57          */
58         private $databaseSetupDone = false;
60         /**
61          * string $oldTablePrefix Original table prefix
62          */
63         private $oldTablePrefix;
65         /**
66          * Sets terminal colorization and diff/quick modes depending on OS and
67          * command-line options (--color and --quick).
68          */
69         public function ParserTest() {
70                 global $options;
72                 # Only colorize output if stdout is a terminal.
73                 $this->color = !wfIsWindows() && posix_isatty(1);
75                 if( isset( $options['color'] ) ) {
76                         switch( $options['color'] ) {
77                         case 'no':
78                                 $this->color = false;
79                                 break;
80                         case 'yes':
81                         default:
82                                 $this->color = true;
83                                 break;
84                         }
85                 }
86                 $this->term = $this->color
87                         ? new AnsiTermColorer()
88                         : new DummyTermColorer();
90                 $this->showDiffs = !isset( $options['quick'] );
91                 $this->showProgress = !isset( $options['quiet'] );
92                 $this->showFailure = !(
93                         isset( $options['quiet'] )
94                         && ( isset( $options['record'] )
95                                 || isset( $options['compare'] ) ) ); // redundant output
96                 
97                 $this->showOutput = isset( $options['show-output'] );
100                 if (isset($options['regex'])) {
101                         if ( isset( $options['record'] ) ) {
102                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
103                                 unset( $options['record'] );
104                         }
105                         $this->regex = $options['regex'];
106                 } else {
107                         # Matches anything
108                         $this->regex = '';
109                 }
111                 if( isset( $options['record'] ) ) {
112                         $this->recorder = new DbTestRecorder( $this );
113                 } elseif( isset( $options['compare'] ) ) {
114                         $this->recorder = new DbTestPreviewer( $this );
115                 } else {
116                         $this->recorder = new TestRecorder( $this );
117                 }
118                 $this->keepUploads = isset( $options['keep-uploads'] );
120                 $this->hooks = array();
121                 $this->functionHooks = array();
122         }
124         /**
125          * Remove last character if it is a newline
126          */
127         private function chomp($s) {
128                 if (substr($s, -1) === "\n") {
129                         return substr($s, 0, -1);
130                 }
131                 else {
132                         return $s;
133                 }
134         }
136         /**
137          * Run a series of tests listed in the given text files.
138          * Each test consists of a brief description, wikitext input,
139          * and the expected HTML output.
140          *
141          * Prints status updates on stdout and counts up the total
142          * number and percentage of passed tests.
143          *
144          * @param array of strings $filenames
145          * @return bool True if passed all tests, false if any tests failed.
146          */
147         public function runTestsFromFiles( $filenames ) {
148                 $this->recorder->start();
149                 $this->setupDatabase();
150                 $ok = true;
151                 foreach( $filenames as $filename ) {
152                         $ok = $this->runFile( $filename ) && $ok;
153                 }
154                 $this->teardownDatabase();
155                 $this->recorder->report();
156                 $this->recorder->end();
157                 return $ok;
158         }
160         private function runFile( $filename ) {
161                 $infile = fopen( $filename, 'rt' );
162                 if( !$infile ) {
163                         wfDie( "Couldn't open $filename\n" );
164                 } else {
165                         global $IP;
166                         $relative = wfRelativePath( $filename, $IP );
167                         $this->showRunFile( $relative );
168                 }
170                 $data = array();
171                 $section = null;
172                 $n = 0;
173                 $ok = true;
174                 while( false !== ($line = fgets( $infile ) ) ) {
175                         $n++;
176                         $matches = array();
177                         if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
178                                 $section = strtolower( $matches[1] );
179                                 if( $section == 'endarticle') {
180                                         if( !isset( $data['text'] ) ) {
181                                                 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
182                                         }
183                                         if( !isset( $data['article'] ) ) {
184                                                 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
185                                         }
186                                         $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
187                                         $data = array();
188                                         $section = null;
189                                         continue;
190                                 }
191                                 if( $section == 'endhooks' ) {
192                                         if( !isset( $data['hooks'] ) ) {
193                                                 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
194                                         }
195                                         foreach( explode( "\n", $data['hooks'] ) as $line ) {
196                                                 $line = trim( $line );
197                                                 if( $line ) {
198                                                         $this->requireHook( $line );
199                                                 }
200                                         }
201                                         $data = array();
202                                         $section = null;
203                                         continue;
204                                 }
205                                 if( $section == 'endfunctionhooks' ) {
206                                         if( !isset( $data['functionhooks'] ) ) {
207                                                 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
208                                         }
209                                         foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
210                                                 $line = trim( $line );
211                                                 if( $line ) {
212                                                         $this->requireFunctionHook( $line );
213                                                 }
214                                         }
215                                         $data = array();
216                                         $section = null;
217                                         continue;
218                                 }
219                                 if( $section == 'end' ) {
220                                         if( !isset( $data['test'] ) ) {
221                                                 wfDie( "'end' without 'test' at line $n of $filename\n" );
222                                         }
223                                         if( !isset( $data['input'] ) ) {
224                                                 wfDie( "'end' without 'input' at line $n of $filename\n" );
225                                         }
226                                         if( !isset( $data['result'] ) ) {
227                                                 wfDie( "'end' without 'result' at line $n of $filename\n" );
228                                         }
229                                         if( !isset( $data['options'] ) ) {
230                                                 $data['options'] = '';
231                                         }
232                                         else {
233                                                 $data['options'] = $this->chomp( $data['options'] );
234                                         }
235                                         if (preg_match('/\\bdisabled\\b/i', $data['options'])
236                                                 || !preg_match("/{$this->regex}/i", $data['test'])) {
237                                                 # disabled test
238                                                 $data = array();
239                                                 $section = null;
240                                                 continue;
241                                         }
242                                         $result = $this->runTest(
243                                                 $this->chomp( $data['test'] ),
244                                                 $this->chomp( $data['input'] ),
245                                                 $this->chomp( $data['result'] ),
246                                                 $this->chomp( $data['options'] ) );
247                                         $ok = $ok && $result;
248                                         $this->recorder->record( $this->chomp( $data['test'] ), $result );
249                                         $data = array();
250                                         $section = null;
251                                         continue;
252                                 }
253                                 if ( isset ($data[$section] ) ) {
254                                         wfDie( "duplicate section '$section' at line $n of $filename\n" );
255                                 }
256                                 $data[$section] = '';
257                                 continue;
258                         }
259                         if( $section ) {
260                                 $data[$section] .= $line;
261                         }
262                 }
263                 if ( $this->showProgress ) {
264                         print "\n";
265                 }
266                 return $ok;
267         }
269         /**
270          * Run a given wikitext input through a freshly-constructed wiki parser,
271          * and compare the output against the expected results.
272          * Prints status and explanatory messages to stdout.
273          *
274          * @param string $input Wikitext to try rendering
275          * @param string $result Result to output
276          * @return bool
277          */
278         private function runTest( $desc, $input, $result, $opts ) {
279                 global $wgParserConf;
280                 if( $this->showProgress ) {
281                         $this->showTesting( $desc );
282                 }
284                 $this->setupGlobals($opts);
286                 $user = new User();
287                 $options = ParserOptions::newFromUser( $user );
289                 if (preg_match('/\\bmath\\b/i', $opts)) {
290                         # XXX this should probably be done by the ParserOptions
291                         $options->setUseTex(true);
292                 }
294                 $m = array();
295                 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
296                         $titleText = $m[1];
297                 }
298                 else {
299                         $titleText = 'Parser test';
300                 }
302                 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
304                 $class = $wgParserConf['class'];
305                 $parser = new $class( $wgParserConf );
306                 foreach( $this->hooks as $tag => $callback ) {
307                         $parser->setHook( $tag, $callback );
308                 }
309                 foreach( $this->functionHooks as $tag => $bits ) {
310                         list( $callback, $flags ) = $bits;
311                         $parser->setFunctionHook( $tag, $callback, $flags );
312                 }
313                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
315                 $title =& Title::makeTitle( NS_MAIN, $titleText );
317                 $matches = array();
318                 if (preg_match('/\\bpst\\b/i', $opts)) {
319                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
320                 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
321                         $out = $parser->transformMsg( $input, $options );
322                 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
323                         $section = $matches[1];
324                         $out = $parser->getSection( $input, $section );
325                 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
326                         $section = $matches[1];
327                         $replace = $matches[2];
328                         $out = $parser->replaceSection( $input, $section, $replace );
329                 } else {
330                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
331                         $out = $output->getText();
333                         if (preg_match('/\\bill\\b/i', $opts)) {
334                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
335                         } else if (preg_match('/\\bcat\\b/i', $opts)) {
336                                 global $wgOut;
337                                 $wgOut->addCategoryLinks($output->getCategories());
338                                 $cats = $wgOut->getCategoryLinks();
339                                 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
340                         }
342                         $result = $this->tidy($result);
343                 }
345                 $this->teardownGlobals();
347                 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
348                         return $this->showSuccess( $desc );
349                 } else {
350                         return $this->showFailure( $desc, $result, $out );
351                 }
352         }
355         /**
356          * Use a regex to find out the value of an option
357          * @param $regex A regex, the first group will be the value returned
358          * @param $opts Options line to look in
359          * @param $defaults Default value returned if the regex does not match
360          */
361         private static function getOptionValue( $regex, $opts, $default ) {
362                 $m = array();
363                 if( preg_match( $regex, $opts, $m ) ) {
364                         return $m[1];
365                 } else {
366                         return $default;
367                 }
368         }
370         /**
371          * Set up the global variables for a consistent environment for each test.
372          * Ideally this should replace the global configuration entirely.
373          */
374         private function setupGlobals($opts = '') {
375                 if( !isset( $this->uploadDir ) ) {
376                         $this->uploadDir = $this->setupUploadDir();
377                 }
379                 # Find out values for some special options.
380                 $lang =
381                         self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
382                 $variant =
383                         self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
384                 $maxtoclevel =
385                         self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
387                 $settings = array(
388                         'wgServer' => 'http://localhost',
389                         'wgScript' => '/index.php',
390                         'wgScriptPath' => '/',
391                         'wgArticlePath' => '/wiki/$1',
392                         'wgActionPaths' => array(),
393                         'wgLocalFileRepo' => array(
394                                 'class' => 'LocalRepo',
395                                 'name' => 'local',
396                                 'directory' => $this->uploadDir,
397                                 'url' => 'http://example.com/images',
398                                 'hashLevels' => 2,
399                                 'transformVia404' => false,
400                         ),
401                         'wgEnableUploads' => true,
402                         'wgStyleSheetPath' => '/skins',
403                         'wgSitename' => 'MediaWiki',
404                         'wgServerName' => 'Britney Spears',
405                         'wgLanguageCode' => $lang,
406                         'wgContLanguageCode' => $lang,
407                         'wgDBprefix' => 'parsertest_',
408                         'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
409                         'wgLang' => null,
410                         'wgContLang' => null,
411                         'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
412                         'wgMaxTocLevel' => $maxtoclevel,
413                         'wgCapitalLinks' => true,
414                         'wgNoFollowLinks' => true,
415                         'wgThumbnailScriptPath' => false,
416                         'wgUseTeX' => false,
417                         'wgLocaltimezone' => 'UTC',
418                         'wgAllowExternalImages' => true,
419                         'wgUseTidy' => false,
420                         'wgDefaultLanguageVariant' => $variant,
421                         'wgVariantArticlePath' => false,
422                         'wgGroupPermissions' => array( '*' => array(
423                                 'createaccount' => true,
424                                 'read'          => true,
425                                 'edit'          => true,
426                                 'createpage'    => true,
427                                 'createtalk'    => true,
428                         ) ),
429                         'wgDefaultExternalStore' => array(),
430                         'wgForeignFileRepos' => array(),
431                         );
432                 $this->savedGlobals = array();
433                 foreach( $settings as $var => $val ) {
434                         $this->savedGlobals[$var] = $GLOBALS[$var];
435                         $GLOBALS[$var] = $val;
436                 }
437                 $langObj = Language::factory( $lang );
438                 $GLOBALS['wgLang'] = $langObj;
439                 $GLOBALS['wgContLang'] = $langObj;
441                 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
443                 global $wgUser;
444                 $wgUser = new User();
445         }
447         /**
448          * List of temporary tables to create, without prefix.
449          * Some of these probably aren't necessary.
450          */
451         private function listTables() {
452                 global $wgDBtype;
453                 $tables = array('user', 'page', 'page_restrictions',
454                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
455                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
456                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
457                         'recentchanges', 'watchlist', 'math', 'interwiki',
458                         'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
459                         'archive', 'user_groups', 'page_props', 'category'
460                 );
462                 if ($wgDBtype === 'mysql') 
463                         array_push( $tables, 'searchindex' );
464                 
465                 // Allow extensions to add to the list of tables to duplicate;
466                 // may be necessary if they hook into page save or other code
467                 // which will require them while running tests.
468                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
470                 return $tables;
471         }
473         /**
474          * Set up a temporary set of wiki tables to work with for the tests.
475          * Currently this will only be done once per run, and any changes to
476          * the db will be visible to later tests in the run.
477          */
478         private function setupDatabase() {
479                 global $wgDBprefix;
480                 if ( $this->databaseSetupDone ) {
481                         return;
482                 }
483                 if ( $wgDBprefix === 'parsertest_' ) {
484                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
485                 }
486                 $this->databaseSetupDone = true;
487                 $this->oldTablePrefix = $wgDBprefix;
489                 # CREATE TEMPORARY TABLE breaks if there is more than one server
490                 if ( wfGetLB()->getServerCount() != 1 ) {
491                         $this->useTemporaryTables = false;
492                 }
494                 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
496                 $db = wfGetDB( DB_MASTER );
497                 $tables = $this->listTables();
499                 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
500                         # Database that supports CREATE TABLE ... LIKE
501                         global $wgDBtype;
502                         if( $wgDBtype == 'postgres' ) {
503                                 $def = 'INCLUDING DEFAULTS';
504                         } else {
505                                 $def = '';
506                         }
507                         foreach ($tables as $tbl) {
508                                 # Clean up from previous aborted run.  So that table escaping
509                                 # works correctly across DB engines, we need to change the pre-
510                                 # fix back and forth so tableName() works right.
511                                 $this->changePrefix( $this->oldTablePrefix );
512                                 $oldTableName = $db->tableName( $tbl );
513                                 $this->changePrefix( 'parsertest_' );
514                                 $newTableName = $db->tableName( $tbl );
516                                 if ( $db->tableExists( $tbl ) ) {
517                                         $db->query("DROP TABLE $newTableName");
518                                 }
519                                 # Create new table
520                                 $db->query("CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)");
521                         }
522                 } else {
523                         # Hack for MySQL versions < 4.1, which don't support
524                         # "CREATE TABLE ... LIKE". Note that
525                         # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
526                         # would not create the indexes we need....
527                         #
528                         # Note that we don't bother changing around the prefixes here be-
529                         # cause we know we're using MySQL anyway.
530                         foreach ($tables as $tbl) {
531                                 $oldTableName = $db->tableName( $tbl );
532                                 $res = $db->query("SHOW CREATE TABLE $oldTableName");
533                                 $row = $db->fetchRow($res);
534                                 $create = $row[1];
535                                 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 
536                                         "CREATE $temporary TABLE `parsertest_$tbl`", $create);
537                                 if ($create === $create_tmp) {
538                                         # Couldn't do replacement
539                                         wfDie("could not create temporary table $tbl");
540                                 }
541                                 $db->query($create_tmp);
542                         }
543                 }
545                 $this->changePrefix( 'parsertest_' );
547                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
548                 # for testing inter-language links
549                 $db->insert( 'interwiki', array(
550                         array( 'iw_prefix' => 'Wikipedia',
551                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
552                                    'iw_local'  => 0 ),
553                         array( 'iw_prefix' => 'MeatBall',
554                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
555                                    'iw_local'  => 0 ),
556                         array( 'iw_prefix' => 'zh',
557                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
558                                    'iw_local'  => 1 ),
559                         array( 'iw_prefix' => 'es',
560                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
561                                    'iw_local'  => 1 ),
562                         array( 'iw_prefix' => 'fr',
563                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
564                                    'iw_local'  => 1 ),
565                         array( 'iw_prefix' => 'ru',
566                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
567                                    'iw_local'  => 1 ),
568                         ) );
570                 # Hack: Insert an image to work with
571                 $db->insert( 'image', array(
572                         'img_name'        => 'Foobar.jpg',
573                         'img_size'        => 12345,
574                         'img_description' => 'Some lame file',
575                         'img_user'        => 1,
576                         'img_user_text'   => 'WikiSysop',
577                         'img_timestamp'   => $db->timestamp( '20010115123500' ),
578                         'img_width'       => 1941,
579                         'img_height'      => 220,
580                         'img_bits'        => 24,
581                         'img_media_type'  => MEDIATYPE_BITMAP,
582                         'img_major_mime'  => "image",
583                         'img_minor_mime'  => "jpeg",
584                         'img_metadata'    => serialize( array() ),
585                         ) );
587                 # Update certain things in site_stats
588                 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
589         }
591         /**
592          * Change the table prefix on all open DB connections/
593          */
594         protected function changePrefix( $prefix ) {
595                 global $wgDBprefix;
596                 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
597                 $wgDBprefix = $prefix;
598         }
600         public function changeLBPrefix( $lb, $prefix ) {
601                 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
602         }
604         public function changeDBPrefix( $db, $prefix ) {
605                 $db->tablePrefix( $prefix );
606         }
608         private function teardownDatabase() {
609                 global $wgDBprefix;
610                 if ( !$this->databaseSetupDone ) {
611                         return;
612                 }
613                 $this->changePrefix( $this->oldTablePrefix );
614                 $this->databaseSetupDone = false;
615                 if ( $this->useTemporaryTables ) {
616                         # Don't need to do anything
617                         return;
618                 }
620                 $tables = $this->listTables();
621                 $db = wfGetDB( DB_MASTER );
622                 foreach ( $tables as $table ) {
623                         $db->query( "DROP TABLE `parsertest_$table`" );
624                 }
625         }
626         
627         /**
628          * Create a dummy uploads directory which will contain a couple
629          * of files in order to pass existence tests.
630          * @return string The directory
631          */
632         private function setupUploadDir() {
633                 global $IP;
634                 if ( $this->keepUploads ) {
635                         $dir = wfTempDir() . '/mwParser-images';
636                         if ( is_dir( $dir ) ) {
637                                 return $dir;
638                         }
639                 } else {
640                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
641                 }
643                 wfDebug( "Creating upload directory $dir\n" );
644                 mkdir( $dir );
645                 mkdir( $dir . '/3' );
646                 mkdir( $dir . '/3/3a' );
647                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
648                 return $dir;
649         }
651         /**
652          * Restore default values and perform any necessary clean-up
653          * after each test runs.
654          */
655         private function teardownGlobals() {
656                 RepoGroup::destroySingleton();
657                 foreach( $this->savedGlobals as $var => $val ) {
658                         $GLOBALS[$var] = $val;
659                 }
660                 if( isset( $this->uploadDir ) ) {
661                         $this->teardownUploadDir( $this->uploadDir );
662                         unset( $this->uploadDir );
663                 }
664         }
666         /**
667          * Remove the dummy uploads directory
668          */
669         private function teardownUploadDir( $dir ) {
670                 if ( $this->keepUploads ) {
671                         return;
672                 }
674                 // delete the files first, then the dirs.
675                 self::deleteFiles(
676                         array (
677                                 "$dir/3/3a/Foobar.jpg",
678                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
679                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
680                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
681                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
682                         )
683                 );
685                 self::deleteDirs(
686                         array (
687                                 "$dir/3/3a",
688                                 "$dir/3",
689                                 "$dir/thumb/6/65",
690                                 "$dir/thumb/6",
691                                 "$dir/thumb/3/3a/Foobar.jpg",
692                                 "$dir/thumb/3/3a",
693                                 "$dir/thumb/3",
694                                 "$dir/thumb",
695                                 "$dir",
696                         )
697                 );
698         }
700         /**
701          * Delete the specified files, if they exist.
702          * @param array $files full paths to files to delete.
703          */
704         private static function deleteFiles( $files ) {
705                 foreach( $files as $file ) {
706                         if( file_exists( $file ) ) {
707                                 unlink( $file );
708                         }
709                 }
710         }
712         /**
713          * Delete the specified directories, if they exist. Must be empty.
714          * @param array $dirs full paths to directories to delete.
715          */
716         private static function deleteDirs( $dirs ) {
717                 foreach( $dirs as $dir ) {
718                         if( is_dir( $dir ) ) {
719                                 rmdir( $dir );
720                         }
721                 }
722         }
724         /**
725          * "Running test $desc..."
726          */
727         protected function showTesting( $desc ) {
728                 print "Running test $desc... ";
729         }
731         /**
732          * Print a happy success message.
733          *
734          * @param string $desc The test name
735          * @return bool
736          */
737         protected function showSuccess( $desc ) {
738                 if( $this->showProgress ) {
739                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
740                 }
741                 return true;
742         }
744         /**
745          * Print a failure message and provide some explanatory output
746          * about what went wrong if so configured.
747          *
748          * @param string $desc The test name
749          * @param string $result Expected HTML output
750          * @param string $html Actual HTML output
751          * @return bool
752          */
753         protected function showFailure( $desc, $result, $html ) {
754                 if( $this->showFailure ) {
755                         if( !$this->showProgress ) {
756                                 # In quiet mode we didn't show the 'Testing' message before the
757                                 # test, in case it succeeded. Show it now:
758                                 $this->showTesting( $desc );
759                         }
760                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
761                         if ( $this->showOutput ) {
762                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
763                         }
764                         if( $this->showDiffs ) {
765                                 print $this->quickDiff( $result, $html );
766                                 if( !$this->wellFormed( $html ) ) {
767                                         print "XML error: $this->mXmlError\n";
768                                 }
769                         }
770                 }
771                 return false;
772         }
774         /**
775          * Run given strings through a diff and return the (colorized) output.
776          * Requires writable /tmp directory and a 'diff' command in the PATH.
777          *
778          * @param string $input
779          * @param string $output
780          * @param string $inFileTail Tailing for the input file name
781          * @param string $outFileTail Tailing for the output file name
782          * @return string
783          */
784         protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
785                 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
787                 $infile = "$prefix-$inFileTail";
788                 $this->dumpToFile( $input, $infile );
790                 $outfile = "$prefix-$outFileTail";
791                 $this->dumpToFile( $output, $outfile );
793                 $diff = `diff -au $infile $outfile`;
794                 unlink( $infile );
795                 unlink( $outfile );
797                 return $this->colorDiff( $diff );
798         }
800         /**
801          * Write the given string to a file, adding a final newline.
802          *
803          * @param string $data
804          * @param string $filename
805          */
806         private function dumpToFile( $data, $filename ) {
807                 $file = fopen( $filename, "wt" );
808                 fwrite( $file, $data . "\n" );
809                 fclose( $file );
810         }
812         /**
813          * Colorize unified diff output if set for ANSI color output.
814          * Subtractions are colored blue, additions red.
815          *
816          * @param string $text
817          * @return string
818          */
819         protected function colorDiff( $text ) {
820                 return preg_replace(
821                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
822                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
823                                $this->term->color( 31 ) . '$1' . $this->term->reset() ),
824                         $text );
825         }
827         /**
828          * Show "Reading tests from ..."
829          *
830          * @param String $path
831          */
832         protected function showRunFile( $path ){
833                 print $this->term->color( 1 ) .
834                         "Reading tests from \"$path\"..." .
835                         $this->term->reset() .
836                         "\n";
837         }
839         /**
840          * Insert a temporary test article
841          * @param string $name the title, including any prefix
842          * @param string $text the article text
843          * @param int $line the input line number, for reporting errors
844          */
845         private function addArticle($name, $text, $line) {
846                 $this->setupGlobals();
847                 $title = Title::newFromText( $name );
848                 if ( is_null($title) ) {
849                         wfDie( "invalid title at line $line\n" );
850                 }
852                 $aid = $title->getArticleID( GAID_FOR_UPDATE );
853                 if ($aid != 0) {
854                         wfDie( "duplicate article at line $line\n" );
855                 }
857                 $art = new Article($title);
858                 $art->insertNewArticle($text, '', false, false );
859                 $this->teardownGlobals();
860         }
862         /**
863          * Steal a callback function from the primary parser, save it for
864          * application to our scary parser. If the hook is not installed,
865          * die a painful dead to warn the others.
866          * @param string $name
867          */
868         private function requireHook( $name ) {
869                 global $wgParser;
870                 if( isset( $wgParser->mTagHooks[$name] ) ) {
871                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
872                 } else {
873                         wfDie( "This test suite requires the '$name' hook extension.\n" );
874                 }
875         }
877         /**
878          * Steal a callback function from the primary parser, save it for
879          * application to our scary parser. If the hook is not installed,
880          * die a painful dead to warn the others.
881          * @param string $name
882          */
883         private function requireFunctionHook( $name ) {
884                 global $wgParser;
885                 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
886                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
887                 } else {
888                         wfDie( "This test suite requires the '$name' function hook extension.\n" );
889                 }
890         }
892         /*
893          * Run the "tidy" command on text if the $wgUseTidy
894          * global is true
895          *
896          * @param string $text the text to tidy
897          * @return string
898          * @static
899          */
900         private function tidy( $text ) {
901                 global $wgUseTidy;
902                 if ($wgUseTidy) {
903                         $text = Parser::tidy($text);
904                 }
905                 return $text;
906         }
908         private function wellFormed( $text ) {
909                 $html =
910                         Sanitizer::hackDocType() .
911                         '<html>' .
912                         $text .
913                         '</html>';
915                 $parser = xml_parser_create( "UTF-8" );
917                 # case folding violates XML standard, turn it off
918                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
920                 if( !xml_parse( $parser, $html, true ) ) {
921                         $err = xml_error_string( xml_get_error_code( $parser ) );
922                         $position = xml_get_current_byte_index( $parser );
923                         $fragment = $this->extractFragment( $html, $position );
924                         $this->mXmlError = "$err at byte $position:\n$fragment";
925                         xml_parser_free( $parser );
926                         return false;
927                 }
928                 xml_parser_free( $parser );
929                 return true;
930         }
932         private function extractFragment( $text, $position ) {
933                 $start = max( 0, $position - 10 );
934                 $before = $position - $start;
935                 $fragment = '...' .
936                         $this->term->color( 34 ) .
937                         substr( $text, $start, $before ) .
938                         $this->term->color( 0 ) .
939                         $this->term->color( 31 ) .
940                         $this->term->color( 1 ) .
941                         substr( $text, $position, 1 ) .
942                         $this->term->color( 0 ) .
943                         $this->term->color( 34 ) .
944                         substr( $text, $position + 1, 9 ) .
945                         $this->term->color( 0 ) .
946                         '...';
947                 $display = str_replace( "\n", ' ', $fragment );
948                 $caret = '   ' .
949                         str_repeat( ' ', $before ) .
950                         $this->term->color( 31 ) .
951                         '^' .
952                         $this->term->color( 0 );
953                 return "$display\n$caret";
954         }
957 class AnsiTermColorer {
958         function __construct() {
959         }
961         /**
962          * Return ANSI terminal escape code for changing text attribs/color
963          *
964          * @param string $color Semicolon-separated list of attribute/color codes
965          * @return string
966          */
967         public function color( $color ) {
968                 global $wgCommandLineDarkBg;
969                 $light = $wgCommandLineDarkBg ? "1;" : "0;";
970                 return "\x1b[{$light}{$color}m";
971         }
973         /**
974          * Return ANSI terminal escape code for restoring default text attributes
975          *
976          * @return string
977          */
978         public function reset() {
979                 return $this->color( 0 );
980         }
983 /* A colour-less terminal */
984 class DummyTermColorer {
985         public function color( $color ) {
986                 return '';
987         }
989         public function reset() {
990                 return '';
991         }
994 class TestRecorder {
995         var $parent;
996         var $term;
998         function __construct( $parent ) {
999                 $this->parent = $parent;
1000                 $this->term = $parent->term;
1001         }
1003         function start() {
1004                 $this->total = 0;
1005                 $this->success = 0;
1006         }
1008         function record( $test, $result ) {
1009                 $this->total++;
1010                 $this->success += ($result ? 1 : 0);
1011         }
1013         function end() {
1014                 // dummy
1015         }
1017         function report() {
1018                 if( $this->total > 0 ) {
1019                         $this->reportPercentage( $this->success, $this->total );
1020                 } else {
1021                         wfDie( "No tests found.\n" );
1022                 }
1023         }
1025         function reportPercentage( $success, $total ) {
1026                 $ratio = wfPercent( 100 * $success / $total );
1027                 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1028                 if( $success == $total ) {
1029                         print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1030                 } else {
1031                         $failed = $total - $success ;
1032                         print $this->term->color( 31 ) . "$failed tests failed!";
1033                 }
1034                 print $this->term->reset() . "\n";
1035                 return ($success == $total);
1036         }
1039 class DbTestPreviewer extends TestRecorder  {
1040         protected $lb;      ///< Database load balancer
1041         protected $db;      ///< Database connection to the main DB
1042         protected $curRun;  ///< run ID number for the current run
1043         protected $prevRun; ///< run ID number for the previous run, if any
1044         protected $results; ///< Result array
1046         /**
1047          * This should be called before the table prefix is changed
1048          */
1049         function __construct( $parent ) {
1050                 parent::__construct( $parent );
1051                 $this->lb = wfGetLBFactory()->newMainLB();
1052                 // This connection will have the wiki's table prefix, not parsertest_
1053                 $this->db = $this->lb->getConnection( DB_MASTER );
1054         }
1056         /**
1057          * Set up result recording; insert a record for the run with the date
1058          * and all that fun stuff
1059          */
1060         function start() {
1061                 global $wgDBtype, $wgDBprefix;
1062                 parent::start();
1064                 if( ! $this->db->tableExists( 'testrun' ) 
1065                         or ! $this->db->tableExists( 'testitem' ) ) 
1066                 {
1067                         print "WARNING> `testrun` table not found in database.\n";
1068                         $this->prevRun = false;
1069                 } else {
1070                         // We'll make comparisons against the previous run later...
1071                         $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1072                 }
1073                 $this->results = array();
1074         }
1076         function record( $test, $result ) {
1077                 parent::record( $test, $result );
1078                 $this->results[$test] = $result;
1079         }
1081         function report() {
1082                 if( $this->prevRun ) {
1083                         // f = fail, p = pass, n = nonexistent
1084                         // codes show before then after
1085                         $table = array(
1086                                 'fp' => 'previously failing test(s) now PASSING! :)',
1087                                 'pn' => 'previously PASSING test(s) removed o_O',
1088                                 'np' => 'new PASSING test(s) :)',
1090                                 'pf' => 'previously passing test(s) now FAILING! :(',
1091                                 'fn' => 'previously FAILING test(s) removed O_o',
1092                                 'nf' => 'new FAILING test(s) :(',
1093                                 'ff' => 'still FAILING test(s) :(',
1094                         );
1096                         $prevResults = array();
1098                         $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1099                                 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1100                         foreach ( $res as $row ) {
1101                                 if ( !$this->parent->regex 
1102                                         || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1103                                 {
1104                                         $prevResults[$row->ti_name] = $row->ti_success;
1105                                 }
1106                         }
1108                         $combined = array_keys( $this->results + $prevResults );
1110                         # Determine breakdown by change type
1111                         $breakdown = array();
1112                         foreach ( $combined as $test ) {
1113                                 if ( !isset( $prevResults[$test] ) ) {
1114                                         $before = 'n';
1115                                 } elseif ( $prevResults[$test] == 1 ) {
1116                                         $before = 'p';
1117                                 } else /* if ( $prevResults[$test] == 0 )*/ {
1118                                         $before = 'f';
1119                                 }
1120                                 if ( !isset( $this->results[$test] ) ) {
1121                                         $after = 'n';
1122                                 } elseif ( $this->results[$test] == 1 ) {
1123                                         $after = 'p';
1124                                 } else /*if ( $this->results[$test] == 0 ) */ {
1125                                         $after = 'f';
1126                                 }
1127                                 $code = $before . $after;
1128                                 if ( isset( $table[$code] ) ) {
1129                                         $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1130                                 }
1131                         }
1133                         # Write out results
1134                         foreach ( $table as $code => $label ) {
1135                                 if( !empty( $breakdown[$code] ) ) {
1136                                         $count = count($breakdown[$code]);
1137                                         printf( "\n%4d %s\n", $count, $label );
1138                                         foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1139                                                 print "      * $differing_test_name  [$statusInfo]\n";
1140                                         }
1141                                 }
1142                         }
1143                 } else {
1144                         print "No previous test runs to compare against.\n";
1145                 }
1146                 print "\n";
1147                 parent::report();
1148         }
1150         /**
1151          ** Returns a string giving information about when a test last had a status change.
1152          ** Could help to track down when regressions were introduced, as distinct from tests
1153          ** which have never passed (which are more change requests than regressions).
1154          */
1155         private function getTestStatusInfo($testname, $after) {
1157                 // If we're looking at a test that has just been removed, then say when it first appeared.
1158                 if ( $after == 'n' ) {
1159                         $changedRun = $this->db->selectField ( 'testitem',
1160                                                                                                    'MIN(ti_run)',
1161                                                                                                    array( 'ti_name' => $testname ),
1162                                                                                                    __METHOD__ );
1163                         $appear = $this->db->selectRow ( 'testrun',
1164                                                                                          array( 'tr_date', 'tr_mw_version' ),
1165                                                                                          array( 'tr_id' => $changedRun ),
1166                                                                                          __METHOD__ );
1167                         return "First recorded appearance: "
1168                                . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
1169                                .  ", " . $appear->tr_mw_version;
1170                 }
1172                 // Otherwise, this test has previous recorded results.
1173                 // See when this test last had a different result to what we're seeing now.
1174                 $conds = array( 
1175                         'ti_name'    => $testname,
1176                         'ti_success' => ($after == 'f' ? "1" : "0") );
1177                 if ( $this->curRun ) {
1178                         $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1179                 }
1181                 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1183                 // If no record of ever having had a different result.
1184                 if ( is_null ( $changedRun ) ) {
1185                         if ($after == "f") {
1186                                 return "Has never passed";
1187                         } else {
1188                                 return "Has never failed";
1189                         }
1190                 }
1192                 // Otherwise, we're looking at a test whose status has changed.
1193                 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1194                 // In this situation, give as much info as we can as to when it changed status.
1195                 $pre  = $this->db->selectRow ( 'testrun',
1196                                                                                 array( 'tr_date', 'tr_mw_version' ),
1197                                                                                 array( 'tr_id' => $changedRun ),
1198                                                                                 __METHOD__ );
1199                 $post = $this->db->selectRow ( 'testrun',
1200                                                                                 array( 'tr_date', 'tr_mw_version' ),
1201                                                                                 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1202                                                                                 __METHOD__,
1203                                                                                 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1204                                                                          );
1206                 if ( $post ) {
1207                         $postDate = date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) . ", {$post->tr_mw_version}";
1208                 } else {
1209                         $postDate = 'now';
1210                 }
1211                 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1212                                 . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
1213                                 . " and $postDate";
1215         }
1217         /**
1218          * Commit transaction and clean up for result recording
1219          */
1220         function end() {
1221                 $this->lb->commitMasterChanges();
1222                 $this->lb->closeAll();
1223                 parent::end();
1224         }
1228 class DbTestRecorder extends DbTestPreviewer  {
1229         /**
1230          * Set up result recording; insert a record for the run with the date
1231          * and all that fun stuff
1232          */
1233         function start() {
1234                 global $wgDBtype, $wgDBprefix;
1235                 $this->db->begin();
1237                 if( ! $this->db->tableExists( 'testrun' ) 
1238                         or ! $this->db->tableExists( 'testitem' ) ) 
1239                 {
1240                         print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1241                         if ($wgDBtype === 'postgres')
1242                                 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1243                         else
1244                                 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1245                         echo "OK, resuming.\n";
1246                 }
1247                 
1248                 parent::start();
1250                 $this->db->insert( 'testrun',
1251                         array(
1252                                 'tr_date'        => $this->db->timestamp(),
1253                                 'tr_mw_version'  => SpecialVersion::getVersion(),
1254                                 'tr_php_version' => phpversion(),
1255                                 'tr_db_version'  => $this->db->getServerVersion(),
1256                                 'tr_uname'       => php_uname()
1257                         ),
1258                         __METHOD__ );
1259                         if ($wgDBtype === 'postgres')
1260                                 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1261                         else
1262                                 $this->curRun = $this->db->insertId();
1263         }
1265         /**
1266          * Record an individual test item's success or failure to the db
1267          * @param string $test
1268          * @param bool $result
1269          */
1270         function record( $test, $result ) {
1271                 parent::record( $test, $result );
1272                 $this->db->insert( 'testitem',
1273                         array(
1274                                 'ti_run'     => $this->curRun,
1275                                 'ti_name'    => $test,
1276                                 'ti_success' => $result ? 1 : 0,
1277                         ),
1278                         __METHOD__ );
1279         }