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