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