3 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
6 public $runDisabled = false;
9 * $called tracks whether the setUp and tearDown method has been called.
10 * class extending MediaWikiTestCase usually override setUp and tearDown
11 * but forget to call the parent.
13 * The array format takes a method name as key and anything as a value.
14 * By asserting the key exist, we know the child class has called the
17 * This property must be private, we do not want child to override it,
18 * they should call the appropriate parent method instead.
20 private $called = array();
23 * @var Array of TestUser
31 protected $tablesUsed = array(); // tables with data
33 private static $useTemporaryTables = true;
34 private static $reuseDB = false;
35 private static $dbSetup = false;
36 private static $oldTablePrefix = false;
39 * Holds the paths of temporary files/directories created through getNewTempFile,
40 * and getNewTempDirectory
44 private $tmpfiles = array();
47 * Holds original values of MediaWiki configuration settings
48 * to be restored in tearDown().
49 * See also setMwGlobal().
52 private $mwGlobals = array();
55 * Table name prefixes. Oracle likes it shorter.
57 const DB_PREFIX
= 'unittest_';
58 const ORA_DB_PREFIX
= 'ut_';
60 protected $supportedDBs = array(
67 function __construct( $name = null, array $data = array(), $dataName = '' ) {
68 parent
::__construct( $name, $data, $dataName );
70 $this->backupGlobals
= false;
71 $this->backupStaticAttributes
= false;
74 function run( PHPUnit_Framework_TestResult
$result = NULL ) {
75 /* Some functions require some kind of caching, and will end up using the db,
76 * which we can't allow, as that would open a new connection for mysql.
77 * Replace with a HashBag. They would not be going to persist anyway.
79 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
81 $needsResetDB = false;
82 $logName = get_class( $this ) . '::' . $this->getName( false );
84 if( $this->needsDB() ) {
85 // set up a DB connection for this test to use
87 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
88 self
::$reuseDB = $this->getCliArg('reuse-db');
90 $this->db
= wfGetDB( DB_MASTER
);
92 $this->checkDbIsSupported();
94 if( !self
::$dbSetup ) {
95 wfProfileIn( $logName . ' (clone-db)' );
97 // switch to a temporary clone of the database
98 self
::setupTestDB( $this->db
, $this->dbPrefix() );
100 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
104 wfProfileOut( $logName . ' (clone-db)' );
107 wfProfileIn( $logName . ' (prepare-db)' );
108 $this->addCoreDBData();
110 wfProfileOut( $logName . ' (prepare-db)' );
112 $needsResetDB = true;
115 wfProfileIn( $logName );
116 parent
::run( $result );
117 wfProfileOut( $logName );
119 if( $needsResetDB ) {
120 wfProfileIn( $logName . ' (reset-db)' );
122 wfProfileOut( $logName . ' (reset-db)' );
127 * obtains a new temporary file name
129 * The obtained filename is enlisted to be removed upon tearDown
131 * @returns string: absolute name of the temporary file
133 protected function getNewTempFile() {
134 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
135 $this->tmpfiles
[] = $fname;
140 * obtains a new temporary directory
142 * The obtained directory is enlisted to be removed (recursively with all its contained
143 * files) upon tearDown.
145 * @returns string: absolute name of the temporary directory
147 protected function getNewTempDirectory() {
148 // Starting of with a temporary /file/.
149 $fname = $this->getNewTempFile();
151 // Converting the temporary /file/ to a /directory/
153 // The following is not atomic, but at least we now have a single place,
154 // where temporary directory creation is bundled and can be improved
156 $this->assertTrue( wfMkdirParents( $fname ) );
161 * setUp and tearDown should (where significant)
162 * happen in reverse order.
164 protected function setUp() {
165 wfProfileIn( __METHOD__
);
167 $this->called
['setUp'] = 1;
170 //@todo: global variables to restore for *every* test
180 // Cleaning up temporary files
181 foreach ( $this->tmpfiles
as $fname ) {
182 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
184 } elseif ( is_dir( $fname ) ) {
185 wfRecursiveRemoveDir( $fname );
189 // Clean up open transactions
190 if ( $this->needsDB() && $this->db
) {
191 while( $this->db
->trxLevel() > 0 ) {
192 $this->db
->rollback();
196 wfProfileOut( __METHOD__
);
199 protected function tearDown() {
200 wfProfileIn( __METHOD__
);
202 // Cleaning up temporary files
203 foreach ( $this->tmpfiles
as $fname ) {
204 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
206 } elseif ( is_dir( $fname ) ) {
207 wfRecursiveRemoveDir( $fname );
211 // Clean up open transactions
212 if ( $this->needsDB() && $this->db
) {
213 while( $this->db
->trxLevel() > 0 ) {
214 $this->db
->rollback();
218 // Restore mw globals
219 foreach ( $this->mwGlobals
as $key => $value ) {
220 $GLOBALS[$key] = $value;
222 $this->mwGlobals
= array();
225 wfProfileOut( __METHOD__
);
229 * Make sure MediaWikiTestCase extending classes have called their
230 * parent setUp method
232 final public function testMediaWikiTestCaseParentSetupCalled() {
233 $this->assertArrayHasKey( 'setUp', $this->called
,
234 get_called_class() . "::setUp() must call parent::setUp()"
239 * Individual test functions may override globals (either directly or through this
240 * setMwGlobals() function), however one must call this method at least once for
241 * each key within the setUp().
242 * That way the key is added to the array of globals that will be reset afterwards
243 * in the tearDown(). And, equally important, that way all other tests are executed
244 * with the same settings (instead of using the unreliable local settings for most
245 * tests and fix it only for some tests).
249 * protected function setUp() {
250 * $this->setMwGlobals( 'wgRestrictStuff', true );
253 * function testFoo() {}
255 * function testBar() {}
256 * $this->assertTrue( self::getX()->doStuff() );
258 * $this->setMwGlobals( 'wgRestrictStuff', false );
259 * $this->assertTrue( self::getX()->doStuff() );
262 * function testQuux() {}
265 * @param array|string $pairs Key to the global variable, or an array
266 * of key/value pairs.
267 * @param mixed $value Value to set the global to (ignored
268 * if an array is given as first argument).
270 protected function setMwGlobals( $pairs, $value = null ) {
272 // Normalize (string, value) to an array
273 if( is_string( $pairs ) ) {
274 $pairs = array( $pairs => $value );
277 foreach ( $pairs as $key => $value ) {
278 // NOTE: make sure we only save the global once or a second call to
279 // setMwGlobals() on the same global would override the original
281 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
282 $this->mwGlobals
[$key] = $GLOBALS[$key];
285 // Override the global
286 $GLOBALS[$key] = $value;
291 * Merges the given values into a MW global array variable.
292 * Useful for setting some entries in a configuration array, instead of
293 * setting the entire array.
295 * @param String $name The name of the global, as in wgFooBar
296 * @param Array $values The array containing the entries to set in that global
298 * @throws MWException if the designated global is not an array.
300 protected function mergeMwGlobalArrayValue( $name, $values ) {
301 if ( !isset( $GLOBALS[$name] ) ) {
304 if ( !is_array( $GLOBALS[$name] ) ) {
305 throw new MWException( "MW global $name is not an array." );
308 // NOTE: do not use array_merge, it screws up for numeric keys.
309 $merged = $GLOBALS[$name];
310 foreach ( $values as $k => $v ) {
315 $this->setMwGlobals( $name, $merged );
318 function dbPrefix() {
319 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
323 # if the test says it uses database tables, it needs the database
324 if ( $this->tablesUsed
) {
328 # if the test says it belongs to the Database group, it needs the database
329 $rc = new ReflectionClass( $this );
330 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
338 * Stub. If a test needs to add additional data to the database, it should
339 * implement this method and do so
341 function addDBData() {}
343 private function addCoreDBData() {
344 # disabled for performance
345 #$this->tablesUsed[] = 'page';
346 #$this->tablesUsed[] = 'revision';
348 if ( $this->db
->getType() == 'oracle' ) {
350 # Insert 0 user to prevent FK violations
352 $this->db
->insert( 'user', array(
354 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
356 # Insert 0 page to prevent FK violations
358 $this->db
->insert( 'page', array(
360 'page_namespace' => 0,
362 'page_restrictions' => NULL,
364 'page_is_redirect' => 0,
367 'page_touched' => $this->db
->timestamp(),
369 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
373 User
::resetIdByNameCache();
376 $user = User
::newFromName( 'UTSysop' );
378 if ( $user->idForName() == 0 ) {
379 $user->addToDatabase();
380 $user->setPassword( 'UTSysopPassword' );
382 $user->addGroup( 'sysop' );
383 $user->addGroup( 'bureaucrat' );
384 $user->saveSettings();
388 //Make 1 page with 1 revision
389 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
390 if ( !$page->getId() == 0 ) {
391 $page->doEditContent(
392 new WikitextContent( 'UTContent' ),
396 User
::newFromName( 'UTSysop' ) );
401 * Restores MediaWiki to using the table set (table prefix) it was using before
402 * setupTestDB() was called. Useful if we need to perform database operations
403 * after the test run has finished (such as saving logs or profiling info).
405 public static function teardownTestDB() {
406 if ( !self
::$dbSetup ) {
410 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
412 self
::$oldTablePrefix = false;
413 self
::$dbSetup = false;
417 * Creates an empty skeleton of the wiki database by cloning its structure
418 * to equivalent tables using the given $prefix. Then sets MediaWiki to
419 * use the new set of tables (aka schema) instead of the original set.
421 * This is used to generate a dummy table set, typically consisting of temporary
422 * tables, that will be used by tests instead of the original wiki database tables.
424 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
425 * by teardownTestDB() to return the wiki to using the original table set.
427 * @note: this method only works when first called. Subsequent calls have no effect,
428 * even if using different parameters.
430 * @param DatabaseBase $db The database connection
431 * @param String $prefix The prefix to use for the new table set (aka schema).
433 * @throws MWException if the database table prefix is already $prefix
435 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
437 if ( $wgDBprefix === $prefix ) {
438 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
441 if ( self
::$dbSetup ) {
445 $tablesCloned = self
::listTables( $db );
446 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
447 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
449 self
::$dbSetup = true;
450 self
::$oldTablePrefix = $wgDBprefix;
452 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
453 CloneDatabase
::changePrefix( $prefix );
456 $dbClone->cloneTableStructure();
459 if ( $db->getType() == 'oracle' ) {
460 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
465 * Empty all tables so they can be repopulated for tests
467 private function resetDB() {
469 if ( $this->db
->getType() == 'oracle' ) {
470 if ( self
::$useTemporaryTables ) {
471 wfGetLB()->closeAll();
472 $this->db
= wfGetDB( DB_MASTER
);
474 foreach( $this->tablesUsed
as $tbl ) {
475 if( $tbl == 'interwiki') continue;
476 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
480 foreach( $this->tablesUsed
as $tbl ) {
481 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
482 $this->db
->delete( $tbl, '*', __METHOD__
);
488 function __call( $func, $args ) {
489 static $compatibility = array(
490 'assertInternalType' => 'assertType',
491 'assertNotInternalType' => 'assertNotType',
492 'assertInstanceOf' => 'assertType',
493 'assertEmpty' => 'assertEmpty2',
496 if ( method_exists( $this->suite
, $func ) ) {
497 return call_user_func_array( array( $this->suite
, $func ), $args);
498 } elseif ( isset( $compatibility[$func] ) ) {
499 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
501 throw new MWException( "Called non-existant $func method on "
502 . get_class( $this ) );
506 private function assertEmpty2( $value, $msg ) {
507 return $this->assertTrue( $value == '', $msg );
510 static private function unprefixTable( $tableName ) {
512 return substr( $tableName, strlen( $wgDBprefix ) );
515 static private function isNotUnittest( $table ) {
516 return strpos( $table, 'unittest_' ) !== 0;
519 public static function listTables( $db ) {
522 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
523 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
525 // Don't duplicate test tables from the previous fataled run
526 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
528 if ( $db->getType() == 'sqlite' ) {
529 $tables = array_flip( $tables );
530 // these are subtables of searchindex and don't need to be duped/dropped separately
531 unset( $tables['searchindex_content'] );
532 unset( $tables['searchindex_segdir'] );
533 unset( $tables['searchindex_segments'] );
534 $tables = array_flip( $tables );
539 protected function checkDbIsSupported() {
540 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
541 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
545 public function getCliArg( $offset ) {
547 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
548 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
553 public function setCliArg( $offset, $value ) {
555 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
560 * Don't throw a warning if $function is deprecated and called later
562 * @param $function String
565 function hideDeprecated( $function ) {
566 wfSuppressWarnings();
567 wfDeprecated( $function );
572 * Asserts that the given database query yields the rows given by $expectedRows.
573 * The expected rows should be given as indexed (not associative) arrays, with
574 * the values given in the order of the columns in the $fields parameter.
575 * Note that the rows are sorted by the columns given in $fields.
579 * @param $table String|Array the table(s) to query
580 * @param $fields String|Array the columns to include in the result (and to sort by)
581 * @param $condition String|Array "where" condition(s)
582 * @param $expectedRows Array - an array of arrays giving the expected rows.
584 * @throws MWException if this test cases's needsDB() method doesn't return true.
585 * Test cases can use "@group Database" to enable database test support,
586 * or list the tables under testing in $this->tablesUsed, or override the
589 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
590 if ( !$this->needsDB() ) {
591 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
592 ' method should return true. Use @group Database or $this->tablesUsed.');
595 $db = wfGetDB( DB_SLAVE
);
597 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
598 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
602 foreach ( $expectedRows as $expected ) {
603 $r = $res->fetchRow();
604 self
::stripStringKeys( $r );
607 $this->assertNotEmpty( $r, "row #$i missing" );
609 $this->assertEquals( $expected, $r, "row #$i mismatches" );
612 $r = $res->fetchRow();
613 self
::stripStringKeys( $r );
615 $this->assertFalse( $r, "found extra row (after #$i)" );
619 * Utility method taking an array of elements and wrapping
620 * each element in it's own array. Useful for data providers
621 * that only return a single argument.
625 * @param array $elements
629 protected function arrayWrap( array $elements ) {
631 function( $element ) {
632 return array( $element );
639 * Assert that two arrays are equal. By default this means that both arrays need to hold
640 * the same set of values. Using additional arguments, order and associated key can also
641 * be set as relevant.
645 * @param array $expected
646 * @param array $actual
647 * @param boolean $ordered If the order of the values should match
648 * @param boolean $named If the keys should match
650 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
652 $this->objectAssociativeSort( $expected );
653 $this->objectAssociativeSort( $actual );
657 $expected = array_values( $expected );
658 $actual = array_values( $actual );
661 call_user_func_array(
662 array( $this, 'assertEquals' ),
663 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
668 * Put each HTML element on its own line and then equals() the results
670 * Use for nicely formatting of PHPUnit diff output when comparing very
675 * @param String $expected HTML on oneline
676 * @param String $actual HTML on oneline
677 * @param String $msg Optional message
679 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
680 $expected = str_replace( '>', ">\n", $expected );
681 $actual = str_replace( '>', ">\n", $actual );
683 $this->assertEquals( $expected, $actual, $msg );
687 * Does an associative sort that works for objects.
691 * @param array $array
693 protected function objectAssociativeSort( array &$array ) {
697 return serialize( $a ) > serialize( $b ) ?
1 : -1;
703 * Utility function for eliminating all string keys from an array.
704 * Useful to turn a database result row as returned by fetchRow() into
705 * a pure indexed array.
709 * @param $r mixed the array to remove string keys from.
711 protected static function stripStringKeys( &$r ) {
712 if ( !is_array( $r ) ) {
716 foreach ( $r as $k => $v ) {
717 if ( is_string( $k ) ) {
724 * Asserts that the provided variable is of the specified
725 * internal type or equals the $value argument. This is useful
726 * for testing return types of functions that return a certain
727 * type or *value* when not set or on error.
731 * @param string $type
732 * @param mixed $actual
733 * @param mixed $value
734 * @param string $message
736 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
737 if ( $actual === $value ) {
738 $this->assertTrue( true, $message );
741 $this->assertType( $type, $actual, $message );
746 * Asserts the type of the provided value. This can be either
747 * in internal type such as boolean or integer, or a class or
748 * interface the value extends or implements.
752 * @param string $type
753 * @param mixed $actual
754 * @param string $message
756 protected function assertType( $type, $actual, $message = '' ) {
757 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
758 $this->assertInstanceOf( $type, $actual, $message );
761 $this->assertInternalType( $type, $actual, $message );
766 * Returns true iff the given namespace defaults to Wikitext
767 * according to $wgNamespaceContentModels
769 * @param int $ns The namespace ID to check
774 protected function isWikitextNS( $ns ) {
775 global $wgNamespaceContentModels;
777 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
778 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
785 * Returns the ID of a namespace that defaults to Wikitext.
786 * Throws an MWException if there is none.
788 * @return int the ID of the wikitext Namespace
791 protected function getDefaultWikitextNS() {
792 global $wgNamespaceContentModels;
794 static $wikitextNS = null; // this is not going to change
795 if ( $wikitextNS !== null ) {
799 // quickly short out on most common case:
800 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
804 // NOTE: prefer content namespaces
805 $namespaces = array_unique( array_merge(
806 MWNamespace
::getContentNamespaces(),
807 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
808 MWNamespace
::getValidNamespaces()
811 $namespaces = array_diff( $namespaces, array(
812 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
815 $talk = array_filter( $namespaces, function ( $ns ) {
816 return MWNamespace
::isTalk( $ns );
819 // prefer non-talk pages
820 $namespaces = array_diff( $namespaces, $talk );
821 $namespaces = array_merge( $namespaces, $talk );
823 // check default content model of each namespace
824 foreach ( $namespaces as $ns ) {
825 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
826 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
) {
834 // @todo: Inside a test, we could skip the test as incomplete.
835 // But frequently, this is used in fixture setup.
836 throw new MWException( "No namespace defaults to wikitext!" );
840 * Check, if $wgDiff3 is set and ready to merge
841 * Will mark the calling test as skipped, if not ready
845 protected function checkHasDiff3() {
848 # This check may also protect against code injection in
849 # case of broken installations.
850 wfSuppressWarnings();
851 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
855 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
860 * Asserts that an exception of the specified type occurs when running
865 * @param callable $code
866 * @param string $expected
867 * @param string $message
869 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
873 call_user_func( $code );
875 catch ( Exception
$pokemons ) {
876 // Gotta Catch 'Em All!
879 if ( $message === '' ) {
880 $message = 'An exception of type "' . $expected . '" should have been thrown';
883 $this->assertInstanceOf( $expected, $pokemons, $message );