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