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