Stash global only once per test case.
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
4 public $suite;
5 public $regex = '';
6 public $runDisabled = false;
7
8 /**
9 * @var Array of TestUser
10 */
11 public static $users;
12
13 /**
14 * @var DatabaseBase
15 */
16 protected $db;
17 protected $oldTablePrefix;
18 protected $useTemporaryTables = true;
19 protected $reuseDB = false;
20 protected $tablesUsed = array(); // tables with data
21
22 private static $dbSetup = false;
23
24 /**
25 * Holds the paths of temporary files/directories created through getNewTempFile,
26 * and getNewTempDirectory
27 *
28 * @var array
29 */
30 private $tmpfiles = array();
31
32 /**
33 * Holds original values of MediaWiki configuration settings
34 * to be restored in tearDown().
35 * See also setMwGlobal().
36 * @var array
37 */
38 private $mwGlobals = array();
39
40 /**
41 * Table name prefixes. Oracle likes it shorter.
42 */
43 const DB_PREFIX = 'unittest_';
44 const ORA_DB_PREFIX = 'ut_';
45
46 protected $supportedDBs = array(
47 'mysql',
48 'sqlite',
49 'postgres',
50 'oracle'
51 );
52
53 function __construct( $name = null, array $data = array(), $dataName = '' ) {
54 parent::__construct( $name, $data, $dataName );
55
56 $this->backupGlobals = false;
57 $this->backupStaticAttributes = false;
58 }
59
60 function run( PHPUnit_Framework_TestResult $result = NULL ) {
61 /* Some functions require some kind of caching, and will end up using the db,
62 * which we can't allow, as that would open a new connection for mysql.
63 * Replace with a HashBag. They would not be going to persist anyway.
64 */
65 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
66
67 if( $this->needsDB() ) {
68 global $wgDBprefix;
69
70 $this->useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
71 $this->reuseDB = $this->getCliArg('reuse-db');
72
73 $this->db = wfGetDB( DB_MASTER );
74
75 $this->checkDbIsSupported();
76
77 $this->oldTablePrefix = $wgDBprefix;
78
79 if( !self::$dbSetup ) {
80 $this->initDB();
81 self::$dbSetup = true;
82 }
83
84 $this->addCoreDBData();
85 $this->addDBData();
86
87 parent::run( $result );
88
89 $this->resetDB();
90 } else {
91 parent::run( $result );
92 }
93 }
94
95 /**
96 * obtains a new temporary file name
97 *
98 * The obtained filename is enlisted to be removed upon tearDown
99 *
100 * @returns string: absolute name of the temporary file
101 */
102 protected function getNewTempFile() {
103 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
104 $this->tmpfiles[] = $fname;
105 return $fname;
106 }
107
108 /**
109 * obtains a new temporary directory
110 *
111 * The obtained directory is enlisted to be removed (recursively with all its contained
112 * files) upon tearDown.
113 *
114 * @returns string: absolute name of the temporary directory
115 */
116 protected function getNewTempDirectory() {
117 // Starting of with a temporary /file/.
118 $fname = $this->getNewTempFile();
119
120 // Converting the temporary /file/ to a /directory/
121 //
122 // The following is not atomic, but at least we now have a single place,
123 // where temporary directory creation is bundled and can be improved
124 unlink( $fname );
125 $this->assertTrue( wfMkdirParents( $fname ) );
126 return $fname;
127 }
128
129 /**
130 * setUp and tearDown should (where significant)
131 * happen in reverse order.
132 */
133 protected function setUp() {
134 parent::setUp();
135
136 /*
137 //@todo: global variables to restore for *every* test
138 array(
139 'wgLang',
140 'wgContLang',
141 'wgLanguageCode',
142 'wgUser',
143 'wgTitle',
144 );
145 */
146
147 // Cleaning up temporary files
148 foreach ( $this->tmpfiles as $fname ) {
149 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
150 unlink( $fname );
151 } elseif ( is_dir( $fname ) ) {
152 wfRecursiveRemoveDir( $fname );
153 }
154 }
155
156 // Clean up open transactions
157 if ( $this->needsDB() && $this->db ) {
158 while( $this->db->trxLevel() > 0 ) {
159 $this->db->rollback();
160 }
161 }
162 }
163
164 protected function tearDown() {
165 // Cleaning up temporary files
166 foreach ( $this->tmpfiles as $fname ) {
167 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
168 unlink( $fname );
169 } elseif ( is_dir( $fname ) ) {
170 wfRecursiveRemoveDir( $fname );
171 }
172 }
173
174 // Clean up open transactions
175 if ( $this->needsDB() && $this->db ) {
176 while( $this->db->trxLevel() > 0 ) {
177 $this->db->rollback();
178 }
179 }
180
181 // Restore mw globals
182 foreach ( $this->mwGlobals as $key => $value ) {
183 $GLOBALS[$key] = $value;
184 }
185 $this->mwGlobals = array();
186
187 parent::tearDown();
188 }
189
190 /**
191 * Individual test functions may override globals (either directly or through this
192 * setMwGlobals() function), however one must call this method at least once for
193 * each key within the setUp().
194 * That way the key is added to the array of globals that will be reset afterwards
195 * in the tearDown(). And, equally important, that way all other tests are executed
196 * with the same settings (instead of using the unreliable local settings for most
197 * tests and fix it only for some tests).
198 *
199 * @example
200 * <code>
201 * protected function setUp() {
202 * $this->setMwGlobals( 'wgRestrictStuff', true );
203 * }
204 *
205 * function testFoo() {}
206 *
207 * function testBar() {}
208 * $this->assertTrue( self::getX()->doStuff() );
209 *
210 * $this->setMwGlobals( 'wgRestrictStuff', false );
211 * $this->assertTrue( self::getX()->doStuff() );
212 * }
213 *
214 * function testQuux() {}
215 * </code>
216 *
217 * @param array|string $pairs Key to the global variable, or an array
218 * of key/value pairs.
219 * @param mixed $value Value to set the global to (ignored
220 * if an array is given as first argument).
221 */
222 protected function setMwGlobals( $pairs, $value = null ) {
223
224 // Normalize (string, value) to an array
225 if( is_string( $pairs ) ) {
226 $pairs = array( $pairs => $value );
227 }
228
229 foreach ( $pairs as $key => $value ) {
230 // NOTE: make sure we only save the global once or a second call to
231 // setMwGlobals() on the same global would override the original
232 // value.
233 if ( !array_key_exists( $key, $this->mwGlobals ) ) {
234 $this->mwGlobals[$key] = $GLOBALS[$key];
235 }
236
237 // Override the global
238 $GLOBALS[$key] = $value;
239 }
240 }
241
242 /**
243 * Merges the given values into a MW global array variable.
244 * Useful for setting some entries in a configuration array, instead of
245 * setting the entire array.
246 *
247 * @param String $name The name of the global, as in wgFooBar
248 * @param Array $values The array containing the entries to set in that global
249 *
250 * @throws MWException if the designated global is not an array.
251 */
252 protected function mergeMwGlobalArrayValue( $name, $values ) {
253 if ( !isset( $GLOBALS[$name] ) ) {
254 $merged = $values;
255 } else {
256 if ( !is_array( $GLOBALS[$name] ) ) {
257 throw new MWException( "MW global $name is not an array." );
258 }
259
260 //NOTE: do not use array_merge, it screws up for numeric keys.
261 $merged = $GLOBALS[$name];
262 foreach ( $values as $k => $v ) {
263 $merged[$k] = $v;
264 }
265 }
266
267 $this->setMwGlobals( $name, $merged );
268 }
269
270 function dbPrefix() {
271 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
272 }
273
274 function needsDB() {
275 # if the test says it uses database tables, it needs the database
276 if ( $this->tablesUsed ) {
277 return true;
278 }
279
280 # if the test says it belongs to the Database group, it needs the database
281 $rc = new ReflectionClass( $this );
282 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
283 return true;
284 }
285
286 return false;
287 }
288
289 /**
290 * Stub. If a test needs to add additional data to the database, it should
291 * implement this method and do so
292 */
293 function addDBData() {}
294
295 private function addCoreDBData() {
296 # disabled for performance
297 #$this->tablesUsed[] = 'page';
298 #$this->tablesUsed[] = 'revision';
299
300 if ( $this->db->getType() == 'oracle' ) {
301
302 # Insert 0 user to prevent FK violations
303 # Anonymous user
304 $this->db->insert( 'user', array(
305 'user_id' => 0,
306 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
307
308 # Insert 0 page to prevent FK violations
309 # Blank page
310 $this->db->insert( 'page', array(
311 'page_id' => 0,
312 'page_namespace' => 0,
313 'page_title' => ' ',
314 'page_restrictions' => NULL,
315 'page_counter' => 0,
316 'page_is_redirect' => 0,
317 'page_is_new' => 0,
318 'page_random' => 0,
319 'page_touched' => $this->db->timestamp(),
320 'page_latest' => 0,
321 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
322
323 }
324
325 User::resetIdByNameCache();
326
327 //Make sysop user
328 $user = User::newFromName( 'UTSysop' );
329
330 if ( $user->idForName() == 0 ) {
331 $user->addToDatabase();
332 $user->setPassword( 'UTSysopPassword' );
333
334 $user->addGroup( 'sysop' );
335 $user->addGroup( 'bureaucrat' );
336 $user->saveSettings();
337 }
338
339
340 //Make 1 page with 1 revision
341 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
342 if ( !$page->getId() == 0 ) {
343 $page->doEditContent(
344 new WikitextContent( 'UTContent' ),
345 'UTPageSummary',
346 EDIT_NEW,
347 false,
348 User::newFromName( 'UTSysop' ) );
349 }
350 }
351
352 private function initDB() {
353 global $wgDBprefix;
354 if ( $wgDBprefix === $this->dbPrefix() ) {
355 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
356 }
357
358 $tablesCloned = $this->listTables();
359 $dbClone = new CloneDatabase( $this->db, $tablesCloned, $this->dbPrefix() );
360 $dbClone->useTemporaryTables( $this->useTemporaryTables );
361
362 if ( ( $this->db->getType() == 'oracle' || !$this->useTemporaryTables ) && $this->reuseDB ) {
363 CloneDatabase::changePrefix( $this->dbPrefix() );
364 $this->resetDB();
365 return;
366 } else {
367 $dbClone->cloneTableStructure();
368 }
369
370 if ( $this->db->getType() == 'oracle' ) {
371 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
372 }
373 }
374
375 /**
376 * Empty all tables so they can be repopulated for tests
377 */
378 private function resetDB() {
379 if( $this->db ) {
380 if ( $this->db->getType() == 'oracle' ) {
381 if ( $this->useTemporaryTables ) {
382 wfGetLB()->closeAll();
383 $this->db = wfGetDB( DB_MASTER );
384 } else {
385 foreach( $this->tablesUsed as $tbl ) {
386 if( $tbl == 'interwiki') continue;
387 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
388 }
389 }
390 } else {
391 foreach( $this->tablesUsed as $tbl ) {
392 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
393 $this->db->delete( $tbl, '*', __METHOD__ );
394 }
395 }
396 }
397 }
398
399 function __call( $func, $args ) {
400 static $compatibility = array(
401 'assertInternalType' => 'assertType',
402 'assertNotInternalType' => 'assertNotType',
403 'assertInstanceOf' => 'assertType',
404 'assertEmpty' => 'assertEmpty2',
405 );
406
407 if ( method_exists( $this->suite, $func ) ) {
408 return call_user_func_array( array( $this->suite, $func ), $args);
409 } elseif ( isset( $compatibility[$func] ) ) {
410 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
411 } else {
412 throw new MWException( "Called non-existant $func method on "
413 . get_class( $this ) );
414 }
415 }
416
417 private function assertEmpty2( $value, $msg ) {
418 return $this->assertTrue( $value == '', $msg );
419 }
420
421 static private function unprefixTable( $tableName ) {
422 global $wgDBprefix;
423 return substr( $tableName, strlen( $wgDBprefix ) );
424 }
425
426 static private function isNotUnittest( $table ) {
427 return strpos( $table, 'unittest_' ) !== 0;
428 }
429
430 protected function listTables() {
431 global $wgDBprefix;
432
433 $tables = $this->db->listTables( $wgDBprefix, __METHOD__ );
434 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
435
436 // Don't duplicate test tables from the previous fataled run
437 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
438
439 if ( $this->db->getType() == 'sqlite' ) {
440 $tables = array_flip( $tables );
441 // these are subtables of searchindex and don't need to be duped/dropped separately
442 unset( $tables['searchindex_content'] );
443 unset( $tables['searchindex_segdir'] );
444 unset( $tables['searchindex_segments'] );
445 $tables = array_flip( $tables );
446 }
447 return $tables;
448 }
449
450 protected function checkDbIsSupported() {
451 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
452 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
453 }
454 }
455
456 public function getCliArg( $offset ) {
457
458 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
459 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
460 }
461
462 }
463
464 public function setCliArg( $offset, $value ) {
465
466 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
467
468 }
469
470 /**
471 * Don't throw a warning if $function is deprecated and called later
472 *
473 * @param $function String
474 * @return null
475 */
476 function hideDeprecated( $function ) {
477 wfSuppressWarnings();
478 wfDeprecated( $function );
479 wfRestoreWarnings();
480 }
481
482 /**
483 * Asserts that the given database query yields the rows given by $expectedRows.
484 * The expected rows should be given as indexed (not associative) arrays, with
485 * the values given in the order of the columns in the $fields parameter.
486 * Note that the rows are sorted by the columns given in $fields.
487 *
488 * @since 1.20
489 *
490 * @param $table String|Array the table(s) to query
491 * @param $fields String|Array the columns to include in the result (and to sort by)
492 * @param $condition String|Array "where" condition(s)
493 * @param $expectedRows Array - an array of arrays giving the expected rows.
494 *
495 * @throws MWException if this test cases's needsDB() method doesn't return true.
496 * Test cases can use "@group Database" to enable database test support,
497 * or list the tables under testing in $this->tablesUsed, or override the
498 * needsDB() method.
499 */
500 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
501 if ( !$this->needsDB() ) {
502 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
503 ' method should return true. Use @group Database or $this->tablesUsed.');
504 }
505
506 $db = wfGetDB( DB_SLAVE );
507
508 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
509 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
510
511 $i = 0;
512
513 foreach ( $expectedRows as $expected ) {
514 $r = $res->fetchRow();
515 self::stripStringKeys( $r );
516
517 $i += 1;
518 $this->assertNotEmpty( $r, "row #$i missing" );
519
520 $this->assertEquals( $expected, $r, "row #$i mismatches" );
521 }
522
523 $r = $res->fetchRow();
524 self::stripStringKeys( $r );
525
526 $this->assertFalse( $r, "found extra row (after #$i)" );
527 }
528
529 /**
530 * Utility method taking an array of elements and wrapping
531 * each element in it's own array. Useful for data providers
532 * that only return a single argument.
533 *
534 * @since 1.20
535 *
536 * @param array $elements
537 *
538 * @return array
539 */
540 protected function arrayWrap( array $elements ) {
541 return array_map(
542 function( $element ) {
543 return array( $element );
544 },
545 $elements
546 );
547 }
548
549 /**
550 * Assert that two arrays are equal. By default this means that both arrays need to hold
551 * the same set of values. Using additional arguments, order and associated key can also
552 * be set as relevant.
553 *
554 * @since 1.20
555 *
556 * @param array $expected
557 * @param array $actual
558 * @param boolean $ordered If the order of the values should match
559 * @param boolean $named If the keys should match
560 */
561 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
562 if ( !$ordered ) {
563 $this->objectAssociativeSort( $expected );
564 $this->objectAssociativeSort( $actual );
565 }
566
567 if ( !$named ) {
568 $expected = array_values( $expected );
569 $actual = array_values( $actual );
570 }
571
572 call_user_func_array(
573 array( $this, 'assertEquals' ),
574 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
575 );
576 }
577
578 /**
579 * Put each HTML element on its own line and then equals() the results
580 *
581 * Use for nicely formatting of PHPUnit diff output when comparing very
582 * simple HTML
583 *
584 * @since 1.20
585 *
586 * @param String $expected HTML on oneline
587 * @param String $actual HTML on oneline
588 * @param String $msg Optional message
589 */
590 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
591 $expected = str_replace( '>', ">\n", $expected );
592 $actual = str_replace( '>', ">\n", $actual );
593
594 $this->assertEquals( $expected, $actual, $msg );
595 }
596
597 /**
598 * Does an associative sort that works for objects.
599 *
600 * @since 1.20
601 *
602 * @param array $array
603 */
604 protected function objectAssociativeSort( array &$array ) {
605 uasort(
606 $array,
607 function( $a, $b ) {
608 return serialize( $a ) > serialize( $b ) ? 1 : -1;
609 }
610 );
611 }
612
613 /**
614 * Utility function for eliminating all string keys from an array.
615 * Useful to turn a database result row as returned by fetchRow() into
616 * a pure indexed array.
617 *
618 * @since 1.20
619 *
620 * @param $r mixed the array to remove string keys from.
621 */
622 protected static function stripStringKeys( &$r ) {
623 if ( !is_array( $r ) ) {
624 return;
625 }
626
627 foreach ( $r as $k => $v ) {
628 if ( is_string( $k ) ) {
629 unset( $r[$k] );
630 }
631 }
632 }
633
634 /**
635 * Asserts that the provided variable is of the specified
636 * internal type or equals the $value argument. This is useful
637 * for testing return types of functions that return a certain
638 * type or *value* when not set or on error.
639 *
640 * @since 1.20
641 *
642 * @param string $type
643 * @param mixed $actual
644 * @param mixed $value
645 * @param string $message
646 */
647 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
648 if ( $actual === $value ) {
649 $this->assertTrue( true, $message );
650 }
651 else {
652 $this->assertType( $type, $actual, $message );
653 }
654 }
655
656 /**
657 * Asserts the type of the provided value. This can be either
658 * in internal type such as boolean or integer, or a class or
659 * interface the value extends or implements.
660 *
661 * @since 1.20
662 *
663 * @param string $type
664 * @param mixed $actual
665 * @param string $message
666 */
667 protected function assertType( $type, $actual, $message = '' ) {
668 if ( class_exists( $type ) || interface_exists( $type ) ) {
669 $this->assertInstanceOf( $type, $actual, $message );
670 }
671 else {
672 $this->assertInternalType( $type, $actual, $message );
673 }
674 }
675
676 /**
677 * Returns true iff the given namespace defaults to Wikitext
678 * according to $wgNamespaceContentModels
679 *
680 * @param int $ns The namespace ID to check
681 *
682 * @return bool
683 * @since 1.21
684 */
685 protected function isWikitextNS( $ns ) {
686 global $wgNamespaceContentModels;
687
688 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
689 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
690 }
691
692 return true;
693 }
694
695 /**
696 * Returns the ID of a namespace that defaults to Wikitext.
697 * Throws an MWException if there is none.
698 *
699 * @return int the ID of the wikitext Namespace
700 * @since 1.21
701 */
702 protected function getDefaultWikitextNS() {
703 global $wgNamespaceContentModels;
704
705 static $wikitextNS = null; // this is not going to change
706 if ( $wikitextNS !== null ) {
707 return $wikitextNS;
708 }
709
710 // quickly short out on most common case:
711 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
712 return NS_MAIN;
713 }
714
715 // NOTE: prefer content namespaces
716 $namespaces = array_unique( array_merge(
717 MWNamespace::getContentNamespaces(),
718 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
719 MWNamespace::getValidNamespaces()
720 ) );
721
722 $namespaces = array_diff( $namespaces, array(
723 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
724 ));
725
726 $talk = array_filter( $namespaces, function ( $ns ) {
727 return MWNamespace::isTalk( $ns );
728 } );
729
730 // prefer non-talk pages
731 $namespaces = array_diff( $namespaces, $talk );
732 $namespaces = array_merge( $namespaces, $talk );
733
734 // check default content model of each namespace
735 foreach ( $namespaces as $ns ) {
736 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
737 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT ) {
738
739 $wikitextNS = $ns;
740 return $wikitextNS;
741 }
742 }
743
744 // give up
745 // @todo: Inside a test, we could skip the test as incomplete.
746 // But frequently, this is used in fixture setup.
747 throw new MWException( "No namespace defaults to wikitext!" );
748 }
749 }