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 * @return 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 * @return 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 if ( $this->needsDB() && $this->db
) {
190 // Clean up open transactions
191 while ( $this->db
->trxLevel() > 0 ) {
192 $this->db
->rollback();
195 // don't ignore DB errors
196 $this->db
->ignoreErrors( false );
199 wfProfileOut( __METHOD__
);
202 protected function tearDown() {
203 wfProfileIn( __METHOD__
);
205 // Cleaning up temporary files
206 foreach ( $this->tmpfiles
as $fname ) {
207 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
209 } elseif ( is_dir( $fname ) ) {
210 wfRecursiveRemoveDir( $fname );
214 if ( $this->needsDB() && $this->db
) {
215 // Clean up open transactions
216 while ( $this->db
->trxLevel() > 0 ) {
217 $this->db
->rollback();
220 // don't ignore DB errors
221 $this->db
->ignoreErrors( false );
224 // Restore mw globals
225 foreach ( $this->mwGlobals
as $key => $value ) {
226 $GLOBALS[$key] = $value;
228 $this->mwGlobals
= array();
231 wfProfileOut( __METHOD__
);
235 * Make sure MediaWikiTestCase extending classes have called their
236 * parent setUp method
238 final public function testMediaWikiTestCaseParentSetupCalled() {
239 $this->assertArrayHasKey( 'setUp', $this->called
,
240 get_called_class() . "::setUp() must call parent::setUp()"
245 * Individual test functions may override globals (either directly or through this
246 * setMwGlobals() function), however one must call this method at least once for
247 * each key within the setUp().
248 * That way the key is added to the array of globals that will be reset afterwards
249 * in the tearDown(). And, equally important, that way all other tests are executed
250 * with the same settings (instead of using the unreliable local settings for most
251 * tests and fix it only for some tests).
255 * protected function setUp() {
256 * $this->setMwGlobals( 'wgRestrictStuff', true );
259 * function testFoo() {}
261 * function testBar() {}
262 * $this->assertTrue( self::getX()->doStuff() );
264 * $this->setMwGlobals( 'wgRestrictStuff', false );
265 * $this->assertTrue( self::getX()->doStuff() );
268 * function testQuux() {}
271 * @param array|string $pairs Key to the global variable, or an array
272 * of key/value pairs.
273 * @param mixed $value Value to set the global to (ignored
274 * if an array is given as first argument).
276 protected function setMwGlobals( $pairs, $value = null ) {
278 // Normalize (string, value) to an array
279 if ( is_string( $pairs ) ) {
280 $pairs = array( $pairs => $value );
283 foreach ( $pairs as $key => $value ) {
284 // NOTE: make sure we only save the global once or a second call to
285 // setMwGlobals() on the same global would override the original
287 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
288 $this->mwGlobals
[$key] = $GLOBALS[$key];
291 // Override the global
292 $GLOBALS[$key] = $value;
297 * Merges the given values into a MW global array variable.
298 * Useful for setting some entries in a configuration array, instead of
299 * setting the entire array.
301 * @param String $name The name of the global, as in wgFooBar
302 * @param Array $values The array containing the entries to set in that global
304 * @throws MWException if the designated global is not an array.
306 protected function mergeMwGlobalArrayValue( $name, $values ) {
307 if ( !isset( $GLOBALS[$name] ) ) {
310 if ( !is_array( $GLOBALS[$name] ) ) {
311 throw new MWException( "MW global $name is not an array." );
314 // NOTE: do not use array_merge, it screws up for numeric keys.
315 $merged = $GLOBALS[$name];
316 foreach ( $values as $k => $v ) {
321 $this->setMwGlobals( $name, $merged );
324 function dbPrefix() {
325 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
329 # if the test says it uses database tables, it needs the database
330 if ( $this->tablesUsed
) {
334 # if the test says it belongs to the Database group, it needs the database
335 $rc = new ReflectionClass( $this );
336 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
344 * Stub. If a test needs to add additional data to the database, it should
345 * implement this method and do so
347 function addDBData() {}
349 private function addCoreDBData() {
350 # disabled for performance
351 #$this->tablesUsed[] = 'page';
352 #$this->tablesUsed[] = 'revision';
354 if ( $this->db
->getType() == 'oracle' ) {
356 # Insert 0 user to prevent FK violations
358 $this->db
->insert( 'user', array(
360 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
362 # Insert 0 page to prevent FK violations
364 $this->db
->insert( 'page', array(
366 'page_namespace' => 0,
368 'page_restrictions' => null,
370 'page_is_redirect' => 0,
373 'page_touched' => $this->db
->timestamp(),
375 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
379 User
::resetIdByNameCache();
382 $user = User
::newFromName( 'UTSysop' );
384 if ( $user->idForName() == 0 ) {
385 $user->addToDatabase();
386 $user->setPassword( 'UTSysopPassword' );
388 $user->addGroup( 'sysop' );
389 $user->addGroup( 'bureaucrat' );
390 $user->saveSettings();
394 //Make 1 page with 1 revision
395 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
396 if ( !$page->getId() == 0 ) {
397 $page->doEditContent(
398 new WikitextContent( 'UTContent' ),
402 User
::newFromName( 'UTSysop' ) );
407 * Restores MediaWiki to using the table set (table prefix) it was using before
408 * setupTestDB() was called. Useful if we need to perform database operations
409 * after the test run has finished (such as saving logs or profiling info).
411 public static function teardownTestDB() {
412 if ( !self
::$dbSetup ) {
416 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
418 self
::$oldTablePrefix = false;
419 self
::$dbSetup = false;
423 * Creates an empty skeleton of the wiki database by cloning its structure
424 * to equivalent tables using the given $prefix. Then sets MediaWiki to
425 * use the new set of tables (aka schema) instead of the original set.
427 * This is used to generate a dummy table set, typically consisting of temporary
428 * tables, that will be used by tests instead of the original wiki database tables.
430 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
431 * by teardownTestDB() to return the wiki to using the original table set.
433 * @note: this method only works when first called. Subsequent calls have no effect,
434 * even if using different parameters.
436 * @param DatabaseBase $db The database connection
437 * @param String $prefix The prefix to use for the new table set (aka schema).
439 * @throws MWException if the database table prefix is already $prefix
441 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
443 if ( $wgDBprefix === $prefix ) {
444 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
447 if ( self
::$dbSetup ) {
451 $tablesCloned = self
::listTables( $db );
452 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
453 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
455 self
::$dbSetup = true;
456 self
::$oldTablePrefix = $wgDBprefix;
458 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
459 CloneDatabase
::changePrefix( $prefix );
462 $dbClone->cloneTableStructure();
465 if ( $db->getType() == 'oracle' ) {
466 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
471 * Empty all tables so they can be repopulated for tests
473 private function resetDB() {
475 if ( $this->db
->getType() == 'oracle' ) {
476 if ( self
::$useTemporaryTables ) {
477 wfGetLB()->closeAll();
478 $this->db
= wfGetDB( DB_MASTER
);
480 foreach ( $this->tablesUsed
as $tbl ) {
481 if ( $tbl == 'interwiki' ) {
484 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
488 foreach ( $this->tablesUsed
as $tbl ) {
489 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
492 $this->db
->delete( $tbl, '*', __METHOD__
);
498 function __call( $func, $args ) {
499 static $compatibility = array(
500 'assertInternalType' => 'assertType',
501 'assertNotInternalType' => 'assertNotType',
502 'assertInstanceOf' => 'assertType',
503 'assertEmpty' => 'assertEmpty2',
506 if ( method_exists( $this->suite
, $func ) ) {
507 return call_user_func_array( array( $this->suite
, $func ), $args );
508 } elseif ( isset( $compatibility[$func] ) ) {
509 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
511 throw new MWException( "Called non-existant $func method on "
512 . get_class( $this ) );
516 private function assertEmpty2( $value, $msg ) {
517 return $this->assertTrue( $value == '', $msg );
520 private static function unprefixTable( $tableName ) {
522 return substr( $tableName, strlen( $wgDBprefix ) );
525 private static function isNotUnittest( $table ) {
526 return strpos( $table, 'unittest_' ) !== 0;
529 public static function listTables( $db ) {
532 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
533 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
535 // Don't duplicate test tables from the previous fataled run
536 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
538 if ( $db->getType() == 'sqlite' ) {
539 $tables = array_flip( $tables );
540 // these are subtables of searchindex and don't need to be duped/dropped separately
541 unset( $tables['searchindex_content'] );
542 unset( $tables['searchindex_segdir'] );
543 unset( $tables['searchindex_segments'] );
544 $tables = array_flip( $tables );
549 protected function checkDbIsSupported() {
550 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
551 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
555 public function getCliArg( $offset ) {
557 if ( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
558 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
563 public function setCliArg( $offset, $value ) {
565 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
570 * Don't throw a warning if $function is deprecated and called later
572 * @param $function String
575 function hideDeprecated( $function ) {
576 wfSuppressWarnings();
577 wfDeprecated( $function );
582 * Asserts that the given database query yields the rows given by $expectedRows.
583 * The expected rows should be given as indexed (not associative) arrays, with
584 * the values given in the order of the columns in the $fields parameter.
585 * Note that the rows are sorted by the columns given in $fields.
589 * @param $table String|Array the table(s) to query
590 * @param $fields String|Array the columns to include in the result (and to sort by)
591 * @param $condition String|Array "where" condition(s)
592 * @param $expectedRows Array - an array of arrays giving the expected rows.
594 * @throws MWException if this test cases's needsDB() method doesn't return true.
595 * Test cases can use "@group Database" to enable database test support,
596 * or list the tables under testing in $this->tablesUsed, or override the
599 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
600 if ( !$this->needsDB() ) {
601 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
602 ' method should return true. Use @group Database or $this->tablesUsed.' );
605 $db = wfGetDB( DB_SLAVE
);
607 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
608 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
612 foreach ( $expectedRows as $expected ) {
613 $r = $res->fetchRow();
614 self
::stripStringKeys( $r );
617 $this->assertNotEmpty( $r, "row #$i missing" );
619 $this->assertEquals( $expected, $r, "row #$i mismatches" );
622 $r = $res->fetchRow();
623 self
::stripStringKeys( $r );
625 $this->assertFalse( $r, "found extra row (after #$i)" );
629 * Utility method taking an array of elements and wrapping
630 * each element in it's own array. Useful for data providers
631 * that only return a single argument.
635 * @param array $elements
639 protected function arrayWrap( array $elements ) {
641 function ( $element ) {
642 return array( $element );
649 * Assert that two arrays are equal. By default this means that both arrays need to hold
650 * the same set of values. Using additional arguments, order and associated key can also
651 * be set as relevant.
655 * @param array $expected
656 * @param array $actual
657 * @param boolean $ordered If the order of the values should match
658 * @param boolean $named If the keys should match
660 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
662 $this->objectAssociativeSort( $expected );
663 $this->objectAssociativeSort( $actual );
667 $expected = array_values( $expected );
668 $actual = array_values( $actual );
671 call_user_func_array(
672 array( $this, 'assertEquals' ),
673 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
678 * Put each HTML element on its own line and then equals() the results
680 * Use for nicely formatting of PHPUnit diff output when comparing very
685 * @param String $expected HTML on oneline
686 * @param String $actual HTML on oneline
687 * @param String $msg Optional message
689 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
690 $expected = str_replace( '>', ">\n", $expected );
691 $actual = str_replace( '>', ">\n", $actual );
693 $this->assertEquals( $expected, $actual, $msg );
697 * Does an associative sort that works for objects.
701 * @param array $array
703 protected function objectAssociativeSort( array &$array ) {
706 function ( $a, $b ) {
707 return serialize( $a ) > serialize( $b ) ?
1 : -1;
713 * Utility function for eliminating all string keys from an array.
714 * Useful to turn a database result row as returned by fetchRow() into
715 * a pure indexed array.
719 * @param $r mixed the array to remove string keys from.
721 protected static function stripStringKeys( &$r ) {
722 if ( !is_array( $r ) ) {
726 foreach ( $r as $k => $v ) {
727 if ( is_string( $k ) ) {
734 * Asserts that the provided variable is of the specified
735 * internal type or equals the $value argument. This is useful
736 * for testing return types of functions that return a certain
737 * type or *value* when not set or on error.
741 * @param string $type
742 * @param mixed $actual
743 * @param mixed $value
744 * @param string $message
746 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
747 if ( $actual === $value ) {
748 $this->assertTrue( true, $message );
750 $this->assertType( $type, $actual, $message );
755 * Asserts the type of the provided value. This can be either
756 * in internal type such as boolean or integer, or a class or
757 * interface the value extends or implements.
761 * @param string $type
762 * @param mixed $actual
763 * @param string $message
765 protected function assertType( $type, $actual, $message = '' ) {
766 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
767 $this->assertInstanceOf( $type, $actual, $message );
769 $this->assertInternalType( $type, $actual, $message );
774 * Returns true iff the given namespace defaults to Wikitext
775 * according to $wgNamespaceContentModels
777 * @param int $ns The namespace ID to check
782 protected function isWikitextNS( $ns ) {
783 global $wgNamespaceContentModels;
785 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
786 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
793 * Returns the ID of a namespace that defaults to Wikitext.
794 * Throws an MWException if there is none.
796 * @return int the ID of the wikitext Namespace
799 protected function getDefaultWikitextNS() {
800 global $wgNamespaceContentModels;
802 static $wikitextNS = null; // this is not going to change
803 if ( $wikitextNS !== null ) {
807 // quickly short out on most common case:
808 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
812 // NOTE: prefer content namespaces
813 $namespaces = array_unique( array_merge(
814 MWNamespace
::getContentNamespaces(),
815 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
816 MWNamespace
::getValidNamespaces()
819 $namespaces = array_diff( $namespaces, array(
820 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
823 $talk = array_filter( $namespaces, function ( $ns ) {
824 return MWNamespace
::isTalk( $ns );
827 // prefer non-talk pages
828 $namespaces = array_diff( $namespaces, $talk );
829 $namespaces = array_merge( $namespaces, $talk );
831 // check default content model of each namespace
832 foreach ( $namespaces as $ns ) {
833 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
834 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
843 // @todo: Inside a test, we could skip the test as incomplete.
844 // But frequently, this is used in fixture setup.
845 throw new MWException( "No namespace defaults to wikitext!" );
849 * Check, if $wgDiff3 is set and ready to merge
850 * Will mark the calling test as skipped, if not ready
854 protected function checkHasDiff3() {
857 # This check may also protect against code injection in
858 # case of broken installations.
859 wfSuppressWarnings();
860 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
864 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
869 * Check whether we have the 'gzip' commandline utility, will skip
870 * the test whenever "gzip -V" fails.
872 * Result is cached at the process level.
878 protected function checkHasGzip() {
881 if ( $haveGzip === null ) {
883 wfShellExec( 'gzip -V', $retval );
884 $haveGzip = ( $retval === 0 );
888 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
895 * Check if $extName is a loaded PHP extension, will skip the
896 * test whenever it is not loaded.
900 protected function checkPHPExtension( $extName ) {
901 $loaded = extension_loaded( $extName );
903 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
909 * Asserts that an exception of the specified type occurs when running
914 * @param callable $code
915 * @param string $expected
916 * @param string $message
918 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
922 call_user_func( $code );
923 } catch ( Exception
$pokemons ) {
924 // Gotta Catch 'Em All!
927 if ( $message === '' ) {
928 $message = 'An exception of type "' . $expected . '" should have been thrown';
931 $this->assertInstanceOf( $expected, $pokemons, $message );