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)' );
126 function usesTemporaryTables() {
127 return self
::$useTemporaryTables;
131 * obtains a new temporary file name
133 * The obtained filename is enlisted to be removed upon tearDown
135 * @return string: absolute name of the temporary file
137 protected function getNewTempFile() {
138 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
139 $this->tmpfiles
[] = $fname;
145 * obtains a new temporary directory
147 * The obtained directory is enlisted to be removed (recursively with all its contained
148 * files) upon tearDown.
150 * @return string: absolute name of the temporary directory
152 protected function getNewTempDirectory() {
153 // Starting of with a temporary /file/.
154 $fname = $this->getNewTempFile();
156 // Converting the temporary /file/ to a /directory/
158 // The following is not atomic, but at least we now have a single place,
159 // where temporary directory creation is bundled and can be improved
161 $this->assertTrue( wfMkdirParents( $fname ) );
167 * setUp and tearDown should (where significant)
168 * happen in reverse order.
170 protected function setUp() {
171 wfProfileIn( __METHOD__
);
173 $this->called
['setUp'] = 1;
176 // @todo global variables to restore for *every* test
186 // Cleaning up temporary files
187 foreach ( $this->tmpfiles
as $fname ) {
188 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
190 } elseif ( is_dir( $fname ) ) {
191 wfRecursiveRemoveDir( $fname );
195 if ( $this->needsDB() && $this->db
) {
196 // Clean up open transactions
197 while ( $this->db
->trxLevel() > 0 ) {
198 $this->db
->rollback();
201 // don't ignore DB errors
202 $this->db
->ignoreErrors( false );
205 wfProfileOut( __METHOD__
);
208 protected function tearDown() {
209 wfProfileIn( __METHOD__
);
211 // Cleaning up temporary files
212 foreach ( $this->tmpfiles
as $fname ) {
213 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
215 } elseif ( is_dir( $fname ) ) {
216 wfRecursiveRemoveDir( $fname );
220 if ( $this->needsDB() && $this->db
) {
221 // Clean up open transactions
222 while ( $this->db
->trxLevel() > 0 ) {
223 $this->db
->rollback();
226 // don't ignore DB errors
227 $this->db
->ignoreErrors( false );
230 // Restore mw globals
231 foreach ( $this->mwGlobals
as $key => $value ) {
232 $GLOBALS[$key] = $value;
234 $this->mwGlobals
= array();
237 wfProfileOut( __METHOD__
);
241 * Make sure MediaWikiTestCase extending classes have called their
242 * parent setUp method
244 final public function testMediaWikiTestCaseParentSetupCalled() {
245 $this->assertArrayHasKey( 'setUp', $this->called
,
246 get_called_class() . "::setUp() must call parent::setUp()"
251 * Individual test functions may override globals (either directly or through this
252 * setMwGlobals() function), however one must call this method at least once for
253 * each key within the setUp().
254 * That way the key is added to the array of globals that will be reset afterwards
255 * in the tearDown(). And, equally important, that way all other tests are executed
256 * with the same settings (instead of using the unreliable local settings for most
257 * tests and fix it only for some tests).
261 * protected function setUp() {
262 * $this->setMwGlobals( 'wgRestrictStuff', true );
265 * function testFoo() {}
267 * function testBar() {}
268 * $this->assertTrue( self::getX()->doStuff() );
270 * $this->setMwGlobals( 'wgRestrictStuff', false );
271 * $this->assertTrue( self::getX()->doStuff() );
274 * function testQuux() {}
277 * @param array|string $pairs Key to the global variable, or an array
278 * of key/value pairs.
279 * @param mixed $value Value to set the global to (ignored
280 * if an array is given as first argument).
282 protected function setMwGlobals( $pairs, $value = null ) {
284 // Normalize (string, value) to an array
285 if ( is_string( $pairs ) ) {
286 $pairs = array( $pairs => $value );
289 foreach ( $pairs as $key => $value ) {
290 // NOTE: make sure we only save the global once or a second call to
291 // setMwGlobals() on the same global would override the original
293 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
294 $this->mwGlobals
[$key] = $GLOBALS[$key];
297 // Override the global
298 $GLOBALS[$key] = $value;
303 * Merges the given values into a MW global array variable.
304 * Useful for setting some entries in a configuration array, instead of
305 * setting the entire array.
307 * @param String $name The name of the global, as in wgFooBar
308 * @param Array $values The array containing the entries to set in that global
310 * @throws MWException if the designated global is not an array.
312 protected function mergeMwGlobalArrayValue( $name, $values ) {
313 if ( !isset( $GLOBALS[$name] ) ) {
316 if ( !is_array( $GLOBALS[$name] ) ) {
317 throw new MWException( "MW global $name is not an array." );
320 // NOTE: do not use array_merge, it screws up for numeric keys.
321 $merged = $GLOBALS[$name];
322 foreach ( $values as $k => $v ) {
327 $this->setMwGlobals( $name, $merged );
330 function dbPrefix() {
331 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
335 # if the test says it uses database tables, it needs the database
336 if ( $this->tablesUsed
) {
340 # if the test says it belongs to the Database group, it needs the database
341 $rc = new ReflectionClass( $this );
342 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
350 * Stub. If a test needs to add additional data to the database, it should
351 * implement this method and do so
353 function addDBData() {
356 private function addCoreDBData() {
357 # disabled for performance
358 #$this->tablesUsed[] = 'page';
359 #$this->tablesUsed[] = 'revision';
361 if ( $this->db
->getType() == 'oracle' ) {
363 # Insert 0 user to prevent FK violations
365 $this->db
->insert( 'user', array(
367 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
369 # Insert 0 page to prevent FK violations
371 $this->db
->insert( 'page', array(
373 'page_namespace' => 0,
375 'page_restrictions' => null,
377 'page_is_redirect' => 0,
380 'page_touched' => $this->db
->timestamp(),
382 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
385 User
::resetIdByNameCache();
388 $user = User
::newFromName( 'UTSysop' );
390 if ( $user->idForName() == 0 ) {
391 $user->addToDatabase();
392 $user->setPassword( 'UTSysopPassword' );
394 $user->addGroup( 'sysop' );
395 $user->addGroup( 'bureaucrat' );
396 $user->saveSettings();
399 //Make 1 page with 1 revision
400 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
401 if ( !$page->getId() == 0 ) {
402 $page->doEditContent(
403 new WikitextContent( 'UTContent' ),
407 User
::newFromName( 'UTSysop' ) );
412 * Restores MediaWiki to using the table set (table prefix) it was using before
413 * setupTestDB() was called. Useful if we need to perform database operations
414 * after the test run has finished (such as saving logs or profiling info).
416 public static function teardownTestDB() {
417 if ( !self
::$dbSetup ) {
421 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
423 self
::$oldTablePrefix = false;
424 self
::$dbSetup = false;
428 * Creates an empty skeleton of the wiki database by cloning its structure
429 * to equivalent tables using the given $prefix. Then sets MediaWiki to
430 * use the new set of tables (aka schema) instead of the original set.
432 * This is used to generate a dummy table set, typically consisting of temporary
433 * tables, that will be used by tests instead of the original wiki database tables.
435 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
436 * by teardownTestDB() to return the wiki to using the original table set.
438 * @note: this method only works when first called. Subsequent calls have no effect,
439 * even if using different parameters.
441 * @param DatabaseBase $db The database connection
442 * @param String $prefix The prefix to use for the new table set (aka schema).
444 * @throws MWException if the database table prefix is already $prefix
446 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
448 if ( $wgDBprefix === $prefix ) {
449 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
452 if ( self
::$dbSetup ) {
456 $tablesCloned = self
::listTables( $db );
457 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
458 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
460 self
::$dbSetup = true;
461 self
::$oldTablePrefix = $wgDBprefix;
463 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
464 CloneDatabase
::changePrefix( $prefix );
468 $dbClone->cloneTableStructure();
471 if ( $db->getType() == 'oracle' ) {
472 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
477 * Empty all tables so they can be repopulated for tests
479 private function resetDB() {
481 if ( $this->db
->getType() == 'oracle' ) {
482 if ( self
::$useTemporaryTables ) {
483 wfGetLB()->closeAll();
484 $this->db
= wfGetDB( DB_MASTER
);
486 foreach ( $this->tablesUsed
as $tbl ) {
487 if ( $tbl == 'interwiki' ) {
490 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
494 foreach ( $this->tablesUsed
as $tbl ) {
495 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
498 $this->db
->delete( $tbl, '*', __METHOD__
);
504 function __call( $func, $args ) {
505 static $compatibility = array(
506 'assertInternalType' => 'assertType',
507 'assertNotInternalType' => 'assertNotType',
508 'assertInstanceOf' => 'assertType',
509 'assertEmpty' => 'assertEmpty2',
512 if ( method_exists( $this->suite
, $func ) ) {
513 return call_user_func_array( array( $this->suite
, $func ), $args );
514 } elseif ( isset( $compatibility[$func] ) ) {
515 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
517 throw new MWException( "Called non-existant $func method on "
518 . get_class( $this ) );
522 private function assertEmpty2( $value, $msg ) {
523 return $this->assertTrue( $value == '', $msg );
526 private static function unprefixTable( $tableName ) {
529 return substr( $tableName, strlen( $wgDBprefix ) );
532 private static function isNotUnittest( $table ) {
533 return strpos( $table, 'unittest_' ) !== 0;
536 public static function listTables( $db ) {
539 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
540 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
542 // Don't duplicate test tables from the previous fataled run
543 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
545 if ( $db->getType() == 'sqlite' ) {
546 $tables = array_flip( $tables );
547 // these are subtables of searchindex and don't need to be duped/dropped separately
548 unset( $tables['searchindex_content'] );
549 unset( $tables['searchindex_segdir'] );
550 unset( $tables['searchindex_segments'] );
551 $tables = array_flip( $tables );
557 protected function checkDbIsSupported() {
558 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
559 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
563 public function getCliArg( $offset ) {
565 if ( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
566 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
570 public function setCliArg( $offset, $value ) {
572 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
576 * Don't throw a warning if $function is deprecated and called later
578 * @param $function String
581 function hideDeprecated( $function ) {
582 wfSuppressWarnings();
583 wfDeprecated( $function );
588 * Asserts that the given database query yields the rows given by $expectedRows.
589 * The expected rows should be given as indexed (not associative) arrays, with
590 * the values given in the order of the columns in the $fields parameter.
591 * Note that the rows are sorted by the columns given in $fields.
595 * @param $table String|Array the table(s) to query
596 * @param $fields String|Array the columns to include in the result (and to sort by)
597 * @param $condition String|Array "where" condition(s)
598 * @param $expectedRows Array - an array of arrays giving the expected rows.
600 * @throws MWException if this test cases's needsDB() method doesn't return true.
601 * Test cases can use "@group Database" to enable database test support,
602 * or list the tables under testing in $this->tablesUsed, or override the
605 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
606 if ( !$this->needsDB() ) {
607 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
608 ' method should return true. Use @group Database or $this->tablesUsed.' );
611 $db = wfGetDB( DB_SLAVE
);
613 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
614 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
618 foreach ( $expectedRows as $expected ) {
619 $r = $res->fetchRow();
620 self
::stripStringKeys( $r );
623 $this->assertNotEmpty( $r, "row #$i missing" );
625 $this->assertEquals( $expected, $r, "row #$i mismatches" );
628 $r = $res->fetchRow();
629 self
::stripStringKeys( $r );
631 $this->assertFalse( $r, "found extra row (after #$i)" );
635 * Utility method taking an array of elements and wrapping
636 * each element in it's own array. Useful for data providers
637 * that only return a single argument.
641 * @param array $elements
645 protected function arrayWrap( array $elements ) {
647 function ( $element ) {
648 return array( $element );
655 * Assert that two arrays are equal. By default this means that both arrays need to hold
656 * the same set of values. Using additional arguments, order and associated key can also
657 * be set as relevant.
661 * @param array $expected
662 * @param array $actual
663 * @param boolean $ordered If the order of the values should match
664 * @param boolean $named If the keys should match
666 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
668 $this->objectAssociativeSort( $expected );
669 $this->objectAssociativeSort( $actual );
673 $expected = array_values( $expected );
674 $actual = array_values( $actual );
677 call_user_func_array(
678 array( $this, 'assertEquals' ),
679 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
684 * Put each HTML element on its own line and then equals() the results
686 * Use for nicely formatting of PHPUnit diff output when comparing very
691 * @param String $expected HTML on oneline
692 * @param String $actual HTML on oneline
693 * @param String $msg Optional message
695 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
696 $expected = str_replace( '>', ">\n", $expected );
697 $actual = str_replace( '>', ">\n", $actual );
699 $this->assertEquals( $expected, $actual, $msg );
703 * Does an associative sort that works for objects.
707 * @param array $array
709 protected function objectAssociativeSort( array &$array ) {
712 function ( $a, $b ) {
713 return serialize( $a ) > serialize( $b ) ?
1 : -1;
719 * Utility function for eliminating all string keys from an array.
720 * Useful to turn a database result row as returned by fetchRow() into
721 * a pure indexed array.
725 * @param $r mixed the array to remove string keys from.
727 protected static function stripStringKeys( &$r ) {
728 if ( !is_array( $r ) ) {
732 foreach ( $r as $k => $v ) {
733 if ( is_string( $k ) ) {
740 * Asserts that the provided variable is of the specified
741 * internal type or equals the $value argument. This is useful
742 * for testing return types of functions that return a certain
743 * type or *value* when not set or on error.
747 * @param string $type
748 * @param mixed $actual
749 * @param mixed $value
750 * @param string $message
752 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
753 if ( $actual === $value ) {
754 $this->assertTrue( true, $message );
756 $this->assertType( $type, $actual, $message );
761 * Asserts the type of the provided value. This can be either
762 * in internal type such as boolean or integer, or a class or
763 * interface the value extends or implements.
767 * @param string $type
768 * @param mixed $actual
769 * @param string $message
771 protected function assertType( $type, $actual, $message = '' ) {
772 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
773 $this->assertInstanceOf( $type, $actual, $message );
775 $this->assertInternalType( $type, $actual, $message );
780 * Returns true iff the given namespace defaults to Wikitext
781 * according to $wgNamespaceContentModels
783 * @param int $ns The namespace ID to check
788 protected function isWikitextNS( $ns ) {
789 global $wgNamespaceContentModels;
791 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
792 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
799 * Returns the ID of a namespace that defaults to Wikitext.
800 * Throws an MWException if there is none.
802 * @return int the ID of the wikitext Namespace
805 protected function getDefaultWikitextNS() {
806 global $wgNamespaceContentModels;
808 static $wikitextNS = null; // this is not going to change
809 if ( $wikitextNS !== null ) {
813 // quickly short out on most common case:
814 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
818 // NOTE: prefer content namespaces
819 $namespaces = array_unique( array_merge(
820 MWNamespace
::getContentNamespaces(),
821 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
822 MWNamespace
::getValidNamespaces()
825 $namespaces = array_diff( $namespaces, array(
826 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
829 $talk = array_filter( $namespaces, function ( $ns ) {
830 return MWNamespace
::isTalk( $ns );
833 // prefer non-talk pages
834 $namespaces = array_diff( $namespaces, $talk );
835 $namespaces = array_merge( $namespaces, $talk );
837 // check default content model of each namespace
838 foreach ( $namespaces as $ns ) {
839 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
840 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
850 // @todo Inside a test, we could skip the test as incomplete.
851 // But frequently, this is used in fixture setup.
852 throw new MWException( "No namespace defaults to wikitext!" );
856 * Check, if $wgDiff3 is set and ready to merge
857 * Will mark the calling test as skipped, if not ready
861 protected function checkHasDiff3() {
864 # This check may also protect against code injection in
865 # case of broken installations.
866 wfSuppressWarnings();
867 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
871 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
876 * Check whether we have the 'gzip' commandline utility, will skip
877 * the test whenever "gzip -V" fails.
879 * Result is cached at the process level.
885 protected function checkHasGzip() {
888 if ( $haveGzip === null ) {
890 wfShellExec( 'gzip -V', $retval );
891 $haveGzip = ( $retval === 0 );
895 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
902 * Check if $extName is a loaded PHP extension, will skip the
903 * test whenever it is not loaded.
907 protected function checkPHPExtension( $extName ) {
908 $loaded = extension_loaded( $extName );
910 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
917 * Asserts that an exception of the specified type occurs when running
922 * @param callable $code
923 * @param string $expected
924 * @param string $message
926 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
930 call_user_func( $code );
931 } catch ( Exception
$pokemons ) {
932 // Gotta Catch 'Em All!
935 if ( $message === '' ) {
936 $message = 'An exception of type "' . $expected . '" should have been thrown';
939 $this->assertInstanceOf( $expected, $pokemons, $message );