3 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
6 public $runDisabled = false;
9 * @var Array of TestUser
17 protected $tablesUsed = array(); // tables with data
19 private static $useTemporaryTables = true;
20 private static $reuseDB = false;
21 private static $dbSetup = false;
22 private static $oldTablePrefix = false;
25 * Holds the paths of temporary files/directories created through getNewTempFile,
26 * and getNewTempDirectory
30 private $tmpfiles = array();
33 * Holds original values of MediaWiki configuration settings
34 * to be restored in tearDown().
35 * See also setMwGlobal().
38 private $mwGlobals = array();
41 * Table name prefixes. Oracle likes it shorter.
43 const DB_PREFIX
= 'unittest_';
44 const ORA_DB_PREFIX
= 'ut_';
46 protected $supportedDBs = array(
53 function __construct( $name = null, array $data = array(), $dataName = '' ) {
54 parent
::__construct( $name, $data, $dataName );
56 $this->backupGlobals
= false;
57 $this->backupStaticAttributes
= false;
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.
65 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
67 $needsResetDB = false;
68 $logName = get_class( $this ) . '::' . $this->getName( false );
70 if( $this->needsDB() ) {
71 // set up a DB connection for this test to use
73 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
74 self
::$reuseDB = $this->getCliArg('reuse-db');
76 $this->db
= wfGetDB( DB_MASTER
);
78 $this->checkDbIsSupported();
80 if( !self
::$dbSetup ) {
81 wfProfileIn( $logName . ' (clone-db)' );
83 // switch to a temporary clone of the database
84 self
::setupTestDB( $this->db
, $this->dbPrefix() );
86 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
90 wfProfileOut( $logName . ' (clone-db)' );
93 wfProfileIn( $logName . ' (prepare-db)' );
94 $this->addCoreDBData();
96 wfProfileOut( $logName . ' (prepare-db)' );
101 wfProfileIn( $logName );
102 parent
::run( $result );
103 wfProfileOut( $logName );
105 if( $needsResetDB ) {
106 wfProfileIn( $logName . ' (reset-db)' );
108 wfProfileOut( $logName . ' (reset-db)' );
113 * obtains a new temporary file name
115 * The obtained filename is enlisted to be removed upon tearDown
117 * @returns string: absolute name of the temporary file
119 protected function getNewTempFile() {
120 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
121 $this->tmpfiles
[] = $fname;
126 * obtains a new temporary directory
128 * The obtained directory is enlisted to be removed (recursively with all its contained
129 * files) upon tearDown.
131 * @returns string: absolute name of the temporary directory
133 protected function getNewTempDirectory() {
134 // Starting of with a temporary /file/.
135 $fname = $this->getNewTempFile();
137 // Converting the temporary /file/ to a /directory/
139 // The following is not atomic, but at least we now have a single place,
140 // where temporary directory creation is bundled and can be improved
142 $this->assertTrue( wfMkdirParents( $fname ) );
147 * setUp and tearDown should (where significant)
148 * happen in reverse order.
150 protected function setUp() {
151 wfProfileIn( __METHOD__
);
155 //@todo: global variables to restore for *every* test
165 // Cleaning up temporary files
166 foreach ( $this->tmpfiles
as $fname ) {
167 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
169 } elseif ( is_dir( $fname ) ) {
170 wfRecursiveRemoveDir( $fname );
174 if ( $this->needsDB() && $this->db
) {
175 // Clean up open transactions
176 while( $this->db
->trxLevel() > 0 ) {
177 $this->db
->rollback();
180 // don't ignore DB errors
181 $this->db
->ignoreErrors( false );
184 wfProfileOut( __METHOD__
);
187 protected function tearDown() {
188 wfProfileIn( __METHOD__
);
190 // Cleaning up temporary files
191 foreach ( $this->tmpfiles
as $fname ) {
192 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
194 } elseif ( is_dir( $fname ) ) {
195 wfRecursiveRemoveDir( $fname );
199 if ( $this->needsDB() && $this->db
) {
200 // Clean up open transactions
201 while( $this->db
->trxLevel() > 0 ) {
202 $this->db
->rollback();
205 // don't ignore DB errors
206 $this->db
->ignoreErrors( false );
209 // Restore mw globals
210 foreach ( $this->mwGlobals
as $key => $value ) {
211 $GLOBALS[$key] = $value;
213 $this->mwGlobals
= array();
216 wfProfileOut( __METHOD__
);
220 * Individual test functions may override globals (either directly or through this
221 * setMwGlobals() function), however one must call this method at least once for
222 * each key within the setUp().
223 * That way the key is added to the array of globals that will be reset afterwards
224 * in the tearDown(). And, equally important, that way all other tests are executed
225 * with the same settings (instead of using the unreliable local settings for most
226 * tests and fix it only for some tests).
230 * protected function setUp() {
231 * $this->setMwGlobals( 'wgRestrictStuff', true );
234 * function testFoo() {}
236 * function testBar() {}
237 * $this->assertTrue( self::getX()->doStuff() );
239 * $this->setMwGlobals( 'wgRestrictStuff', false );
240 * $this->assertTrue( self::getX()->doStuff() );
243 * function testQuux() {}
246 * @param array|string $pairs Key to the global variable, or an array
247 * of key/value pairs.
248 * @param mixed $value Value to set the global to (ignored
249 * if an array is given as first argument).
251 protected function setMwGlobals( $pairs, $value = null ) {
253 // Normalize (string, value) to an array
254 if( is_string( $pairs ) ) {
255 $pairs = array( $pairs => $value );
258 foreach ( $pairs as $key => $value ) {
259 // NOTE: make sure we only save the global once or a second call to
260 // setMwGlobals() on the same global would override the original
262 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
263 $this->mwGlobals
[$key] = $GLOBALS[$key];
266 // Override the global
267 $GLOBALS[$key] = $value;
272 * Merges the given values into a MW global array variable.
273 * Useful for setting some entries in a configuration array, instead of
274 * setting the entire array.
276 * @param String $name The name of the global, as in wgFooBar
277 * @param Array $values The array containing the entries to set in that global
279 * @throws MWException if the designated global is not an array.
281 protected function mergeMwGlobalArrayValue( $name, $values ) {
282 if ( !isset( $GLOBALS[$name] ) ) {
285 if ( !is_array( $GLOBALS[$name] ) ) {
286 throw new MWException( "MW global $name is not an array." );
289 // NOTE: do not use array_merge, it screws up for numeric keys.
290 $merged = $GLOBALS[$name];
291 foreach ( $values as $k => $v ) {
296 $this->setMwGlobals( $name, $merged );
299 function dbPrefix() {
300 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
304 # if the test says it uses database tables, it needs the database
305 if ( $this->tablesUsed
) {
309 # if the test says it belongs to the Database group, it needs the database
310 $rc = new ReflectionClass( $this );
311 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
319 * Stub. If a test needs to add additional data to the database, it should
320 * implement this method and do so
322 function addDBData() {}
324 private function addCoreDBData() {
325 # disabled for performance
326 #$this->tablesUsed[] = 'page';
327 #$this->tablesUsed[] = 'revision';
329 if ( $this->db
->getType() == 'oracle' ) {
331 # Insert 0 user to prevent FK violations
333 $this->db
->insert( 'user', array(
335 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
337 # Insert 0 page to prevent FK violations
339 $this->db
->insert( 'page', array(
341 'page_namespace' => 0,
343 'page_restrictions' => NULL,
345 'page_is_redirect' => 0,
348 'page_touched' => $this->db
->timestamp(),
350 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
354 User
::resetIdByNameCache();
357 $user = User
::newFromName( 'UTSysop' );
359 if ( $user->idForName() == 0 ) {
360 $user->addToDatabase();
361 $user->setPassword( 'UTSysopPassword' );
363 $user->addGroup( 'sysop' );
364 $user->addGroup( 'bureaucrat' );
365 $user->saveSettings();
369 //Make 1 page with 1 revision
370 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
371 if ( !$page->getId() == 0 ) {
372 $page->doEditContent(
373 new WikitextContent( 'UTContent' ),
377 User
::newFromName( 'UTSysop' ) );
382 * Restores MediaWiki to using the table set (table prefix) it was using before
383 * setupTestDB() was called. Useful if we need to perform database operations
384 * after the test run has finished (such as saving logs or profiling info).
386 public static function teardownTestDB() {
387 if ( !self
::$dbSetup ) {
391 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
393 self
::$oldTablePrefix = false;
394 self
::$dbSetup = false;
398 * Creates an empty skeleton of the wiki database by cloning its structure
399 * to equivalent tables using the given $prefix. Then sets MediaWiki to
400 * use the new set of tables (aka schema) instead of the original set.
402 * This is used to generate a dummy table set, typically consisting of temporary
403 * tables, that will be used by tests instead of the original wiki database tables.
405 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
406 * by teardownTestDB() to return the wiki to using the original table set.
408 * @note: this method only works when first called. Subsequent calls have no effect,
409 * even if using different parameters.
411 * @param DatabaseBase $db The database connection
412 * @param String $prefix The prefix to use for the new table set (aka schema).
414 * @throws MWException if the database table prefix is already $prefix
416 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
418 if ( $wgDBprefix === $prefix ) {
419 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
422 if ( self
::$dbSetup ) {
426 $tablesCloned = self
::listTables( $db );
427 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
428 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
430 self
::$dbSetup = true;
431 self
::$oldTablePrefix = $wgDBprefix;
433 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
434 CloneDatabase
::changePrefix( $prefix );
437 $dbClone->cloneTableStructure();
440 if ( $db->getType() == 'oracle' ) {
441 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
446 * Empty all tables so they can be repopulated for tests
448 private function resetDB() {
450 if ( $this->db
->getType() == 'oracle' ) {
451 if ( self
::$useTemporaryTables ) {
452 wfGetLB()->closeAll();
453 $this->db
= wfGetDB( DB_MASTER
);
455 foreach( $this->tablesUsed
as $tbl ) {
456 if( $tbl == 'interwiki') continue;
457 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
461 foreach( $this->tablesUsed
as $tbl ) {
462 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
463 $this->db
->delete( $tbl, '*', __METHOD__
);
469 function __call( $func, $args ) {
470 static $compatibility = array(
471 'assertInternalType' => 'assertType',
472 'assertNotInternalType' => 'assertNotType',
473 'assertInstanceOf' => 'assertType',
474 'assertEmpty' => 'assertEmpty2',
477 if ( method_exists( $this->suite
, $func ) ) {
478 return call_user_func_array( array( $this->suite
, $func ), $args);
479 } elseif ( isset( $compatibility[$func] ) ) {
480 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
482 throw new MWException( "Called non-existant $func method on "
483 . get_class( $this ) );
487 private function assertEmpty2( $value, $msg ) {
488 return $this->assertTrue( $value == '', $msg );
491 static private function unprefixTable( $tableName ) {
493 return substr( $tableName, strlen( $wgDBprefix ) );
496 static private function isNotUnittest( $table ) {
497 return strpos( $table, 'unittest_' ) !== 0;
500 public static function listTables( $db ) {
503 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
504 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
506 // Don't duplicate test tables from the previous fataled run
507 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
509 if ( $db->getType() == 'sqlite' ) {
510 $tables = array_flip( $tables );
511 // these are subtables of searchindex and don't need to be duped/dropped separately
512 unset( $tables['searchindex_content'] );
513 unset( $tables['searchindex_segdir'] );
514 unset( $tables['searchindex_segments'] );
515 $tables = array_flip( $tables );
520 protected function checkDbIsSupported() {
521 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
522 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
526 public function getCliArg( $offset ) {
528 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
529 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
534 public function setCliArg( $offset, $value ) {
536 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
541 * Don't throw a warning if $function is deprecated and called later
543 * @param $function String
546 function hideDeprecated( $function ) {
547 wfSuppressWarnings();
548 wfDeprecated( $function );
553 * Asserts that the given database query yields the rows given by $expectedRows.
554 * The expected rows should be given as indexed (not associative) arrays, with
555 * the values given in the order of the columns in the $fields parameter.
556 * Note that the rows are sorted by the columns given in $fields.
560 * @param $table String|Array the table(s) to query
561 * @param $fields String|Array the columns to include in the result (and to sort by)
562 * @param $condition String|Array "where" condition(s)
563 * @param $expectedRows Array - an array of arrays giving the expected rows.
565 * @throws MWException if this test cases's needsDB() method doesn't return true.
566 * Test cases can use "@group Database" to enable database test support,
567 * or list the tables under testing in $this->tablesUsed, or override the
570 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
571 if ( !$this->needsDB() ) {
572 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
573 ' method should return true. Use @group Database or $this->tablesUsed.');
576 $db = wfGetDB( DB_SLAVE
);
578 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
579 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
583 foreach ( $expectedRows as $expected ) {
584 $r = $res->fetchRow();
585 self
::stripStringKeys( $r );
588 $this->assertNotEmpty( $r, "row #$i missing" );
590 $this->assertEquals( $expected, $r, "row #$i mismatches" );
593 $r = $res->fetchRow();
594 self
::stripStringKeys( $r );
596 $this->assertFalse( $r, "found extra row (after #$i)" );
600 * Utility method taking an array of elements and wrapping
601 * each element in it's own array. Useful for data providers
602 * that only return a single argument.
606 * @param array $elements
610 protected function arrayWrap( array $elements ) {
612 function( $element ) {
613 return array( $element );
620 * Assert that two arrays are equal. By default this means that both arrays need to hold
621 * the same set of values. Using additional arguments, order and associated key can also
622 * be set as relevant.
626 * @param array $expected
627 * @param array $actual
628 * @param boolean $ordered If the order of the values should match
629 * @param boolean $named If the keys should match
631 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
633 $this->objectAssociativeSort( $expected );
634 $this->objectAssociativeSort( $actual );
638 $expected = array_values( $expected );
639 $actual = array_values( $actual );
642 call_user_func_array(
643 array( $this, 'assertEquals' ),
644 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
649 * Put each HTML element on its own line and then equals() the results
651 * Use for nicely formatting of PHPUnit diff output when comparing very
656 * @param String $expected HTML on oneline
657 * @param String $actual HTML on oneline
658 * @param String $msg Optional message
660 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
661 $expected = str_replace( '>', ">\n", $expected );
662 $actual = str_replace( '>', ">\n", $actual );
664 $this->assertEquals( $expected, $actual, $msg );
668 * Does an associative sort that works for objects.
672 * @param array $array
674 protected function objectAssociativeSort( array &$array ) {
678 return serialize( $a ) > serialize( $b ) ?
1 : -1;
684 * Utility function for eliminating all string keys from an array.
685 * Useful to turn a database result row as returned by fetchRow() into
686 * a pure indexed array.
690 * @param $r mixed the array to remove string keys from.
692 protected static function stripStringKeys( &$r ) {
693 if ( !is_array( $r ) ) {
697 foreach ( $r as $k => $v ) {
698 if ( is_string( $k ) ) {
705 * Asserts that the provided variable is of the specified
706 * internal type or equals the $value argument. This is useful
707 * for testing return types of functions that return a certain
708 * type or *value* when not set or on error.
712 * @param string $type
713 * @param mixed $actual
714 * @param mixed $value
715 * @param string $message
717 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
718 if ( $actual === $value ) {
719 $this->assertTrue( true, $message );
722 $this->assertType( $type, $actual, $message );
727 * Asserts the type of the provided value. This can be either
728 * in internal type such as boolean or integer, or a class or
729 * interface the value extends or implements.
733 * @param string $type
734 * @param mixed $actual
735 * @param string $message
737 protected function assertType( $type, $actual, $message = '' ) {
738 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
739 $this->assertInstanceOf( $type, $actual, $message );
742 $this->assertInternalType( $type, $actual, $message );
747 * Returns true iff the given namespace defaults to Wikitext
748 * according to $wgNamespaceContentModels
750 * @param int $ns The namespace ID to check
755 protected function isWikitextNS( $ns ) {
756 global $wgNamespaceContentModels;
758 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
759 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
766 * Returns the ID of a namespace that defaults to Wikitext.
767 * Throws an MWException if there is none.
769 * @return int the ID of the wikitext Namespace
772 protected function getDefaultWikitextNS() {
773 global $wgNamespaceContentModels;
775 static $wikitextNS = null; // this is not going to change
776 if ( $wikitextNS !== null ) {
780 // quickly short out on most common case:
781 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
785 // NOTE: prefer content namespaces
786 $namespaces = array_unique( array_merge(
787 MWNamespace
::getContentNamespaces(),
788 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
789 MWNamespace
::getValidNamespaces()
792 $namespaces = array_diff( $namespaces, array(
793 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
796 $talk = array_filter( $namespaces, function ( $ns ) {
797 return MWNamespace
::isTalk( $ns );
800 // prefer non-talk pages
801 $namespaces = array_diff( $namespaces, $talk );
802 $namespaces = array_merge( $namespaces, $talk );
804 // check default content model of each namespace
805 foreach ( $namespaces as $ns ) {
806 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
807 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
) {
815 // @todo: Inside a test, we could skip the test as incomplete.
816 // But frequently, this is used in fixture setup.
817 throw new MWException( "No namespace defaults to wikitext!" );
821 * Check, if $wgDiff3 is set and ready to merge
822 * Will mark the calling test as skipped, if not ready
826 protected function checkHasDiff3() {
829 # This check may also protect against code injection in
830 # case of broken installations.
831 wfSuppressWarnings();
832 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
836 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
841 * Asserts that an exception of the specified type occurs when running
846 * @param callable $code
847 * @param string $expected
848 * @param string $message
850 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
854 call_user_func( $code );
856 catch ( Exception
$pokemons ) {
857 // Gotta Catch 'Em All!
860 if ( $message === '' ) {
861 $message = 'An exception of type "' . $expected . '" should have been thrown';
864 $this->assertInstanceOf( $expected, $pokemons, $message );