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 if( $this->needsDB() ) {
68 // set up a DB connection for this test to use
70 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
71 self
::$reuseDB = $this->getCliArg('reuse-db');
73 $this->db
= wfGetDB( DB_MASTER
);
75 $this->checkDbIsSupported();
77 if( !self
::$dbSetup ) {
78 // switch to a temporary clone of the database
79 self
::setupTestDB( $this->db
, $this->dbPrefix() );
81 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
86 $this->addCoreDBData();
89 parent
::run( $result );
93 parent
::run( $result );
98 * obtains a new temporary file name
100 * The obtained filename is enlisted to be removed upon tearDown
102 * @returns string: absolute name of the temporary file
104 protected function getNewTempFile() {
105 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
106 $this->tmpfiles
[] = $fname;
111 * obtains a new temporary directory
113 * The obtained directory is enlisted to be removed (recursively with all its contained
114 * files) upon tearDown.
116 * @returns string: absolute name of the temporary directory
118 protected function getNewTempDirectory() {
119 // Starting of with a temporary /file/.
120 $fname = $this->getNewTempFile();
122 // Converting the temporary /file/ to a /directory/
124 // The following is not atomic, but at least we now have a single place,
125 // where temporary directory creation is bundled and can be improved
127 $this->assertTrue( wfMkdirParents( $fname ) );
132 * setUp and tearDown should (where significant)
133 * happen in reverse order.
135 protected function setUp() {
139 //@todo: global variables to restore for *every* test
149 // Cleaning up temporary files
150 foreach ( $this->tmpfiles
as $fname ) {
151 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
153 } elseif ( is_dir( $fname ) ) {
154 wfRecursiveRemoveDir( $fname );
158 // Clean up open transactions
159 if ( $this->needsDB() && $this->db
) {
160 while( $this->db
->trxLevel() > 0 ) {
161 $this->db
->rollback();
166 protected function tearDown() {
167 // Cleaning up temporary files
168 foreach ( $this->tmpfiles
as $fname ) {
169 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
171 } elseif ( is_dir( $fname ) ) {
172 wfRecursiveRemoveDir( $fname );
176 // Clean up open transactions
177 if ( $this->needsDB() && $this->db
) {
178 while( $this->db
->trxLevel() > 0 ) {
179 $this->db
->rollback();
183 // Restore mw globals
184 foreach ( $this->mwGlobals
as $key => $value ) {
185 $GLOBALS[$key] = $value;
187 $this->mwGlobals
= array();
193 * Individual test functions may override globals (either directly or through this
194 * setMwGlobals() function), however one must call this method at least once for
195 * each key within the setUp().
196 * That way the key is added to the array of globals that will be reset afterwards
197 * in the tearDown(). And, equally important, that way all other tests are executed
198 * with the same settings (instead of using the unreliable local settings for most
199 * tests and fix it only for some tests).
203 * protected function setUp() {
204 * $this->setMwGlobals( 'wgRestrictStuff', true );
207 * function testFoo() {}
209 * function testBar() {}
210 * $this->assertTrue( self::getX()->doStuff() );
212 * $this->setMwGlobals( 'wgRestrictStuff', false );
213 * $this->assertTrue( self::getX()->doStuff() );
216 * function testQuux() {}
219 * @param array|string $pairs Key to the global variable, or an array
220 * of key/value pairs.
221 * @param mixed $value Value to set the global to (ignored
222 * if an array is given as first argument).
224 protected function setMwGlobals( $pairs, $value = null ) {
226 // Normalize (string, value) to an array
227 if( is_string( $pairs ) ) {
228 $pairs = array( $pairs => $value );
231 foreach ( $pairs as $key => $value ) {
232 // NOTE: make sure we only save the global once or a second call to
233 // setMwGlobals() on the same global would override the original
235 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
236 $this->mwGlobals
[$key] = $GLOBALS[$key];
239 // Override the global
240 $GLOBALS[$key] = $value;
245 * Merges the given values into a MW global array variable.
246 * Useful for setting some entries in a configuration array, instead of
247 * setting the entire array.
249 * @param String $name The name of the global, as in wgFooBar
250 * @param Array $values The array containing the entries to set in that global
252 * @throws MWException if the designated global is not an array.
254 protected function mergeMwGlobalArrayValue( $name, $values ) {
255 if ( !isset( $GLOBALS[$name] ) ) {
258 if ( !is_array( $GLOBALS[$name] ) ) {
259 throw new MWException( "MW global $name is not an array." );
262 // NOTE: do not use array_merge, it screws up for numeric keys.
263 $merged = $GLOBALS[$name];
264 foreach ( $values as $k => $v ) {
269 $this->setMwGlobals( $name, $merged );
272 function dbPrefix() {
273 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
277 # if the test says it uses database tables, it needs the database
278 if ( $this->tablesUsed
) {
282 # if the test says it belongs to the Database group, it needs the database
283 $rc = new ReflectionClass( $this );
284 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
292 * Stub. If a test needs to add additional data to the database, it should
293 * implement this method and do so
295 function addDBData() {}
297 private function addCoreDBData() {
298 # disabled for performance
299 #$this->tablesUsed[] = 'page';
300 #$this->tablesUsed[] = 'revision';
302 if ( $this->db
->getType() == 'oracle' ) {
304 # Insert 0 user to prevent FK violations
306 $this->db
->insert( 'user', array(
308 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
310 # Insert 0 page to prevent FK violations
312 $this->db
->insert( 'page', array(
314 'page_namespace' => 0,
316 'page_restrictions' => NULL,
318 'page_is_redirect' => 0,
321 'page_touched' => $this->db
->timestamp(),
323 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
327 User
::resetIdByNameCache();
330 $user = User
::newFromName( 'UTSysop' );
332 if ( $user->idForName() == 0 ) {
333 $user->addToDatabase();
334 $user->setPassword( 'UTSysopPassword' );
336 $user->addGroup( 'sysop' );
337 $user->addGroup( 'bureaucrat' );
338 $user->saveSettings();
342 //Make 1 page with 1 revision
343 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
344 if ( !$page->getId() == 0 ) {
345 $page->doEditContent(
346 new WikitextContent( 'UTContent' ),
350 User
::newFromName( 'UTSysop' ) );
355 * Restores MediaWiki to using the table set (table prefix) it was using before
356 * setupTestDB() was called. Useful if we need to perform database operations
357 * after the test run has finished (such as saving logs or profiling info).
359 public static function teardownTestDB() {
360 if ( !self
::$dbSetup ) {
364 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
366 self
::$oldTablePrefix = false;
367 self
::$dbSetup = false;
371 * Creates an empty skeleton of the wiki database by cloning its structure
372 * to equivalent tables using the given $prefix. Then sets MediaWiki to
373 * use the new set of tables (aka schema) instead of the original set.
375 * This is used to generate a dummy table set, typically consisting of temporary
376 * tables, that will be used by tests instead of the original wiki database tables.
378 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
379 * by teardownTestDB() to return the wiki to using the original table set.
381 * @note: this method only works when first called. Subsequent calls have no effect,
382 * even if using different parameters.
384 * @param DatabaseBase $db The database connection
385 * @param String $prefix The prefix to use for the new table set (aka schema).
387 * @throws MWException if the database table prefix is already $prefix
389 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
391 if ( $wgDBprefix === $prefix ) {
392 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
395 if ( self
::$dbSetup ) {
399 $tablesCloned = self
::listTables( $db );
400 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
401 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
403 self
::$dbSetup = true;
404 self
::$oldTablePrefix = $wgDBprefix;
406 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
407 CloneDatabase
::changePrefix( $prefix );
410 $dbClone->cloneTableStructure();
413 if ( $db->getType() == 'oracle' ) {
414 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
419 * Empty all tables so they can be repopulated for tests
421 private function resetDB() {
423 if ( $this->db
->getType() == 'oracle' ) {
424 if ( self
::$useTemporaryTables ) {
425 wfGetLB()->closeAll();
426 $this->db
= wfGetDB( DB_MASTER
);
428 foreach( $this->tablesUsed
as $tbl ) {
429 if( $tbl == 'interwiki') continue;
430 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
434 foreach( $this->tablesUsed
as $tbl ) {
435 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
436 $this->db
->delete( $tbl, '*', __METHOD__
);
442 function __call( $func, $args ) {
443 static $compatibility = array(
444 'assertInternalType' => 'assertType',
445 'assertNotInternalType' => 'assertNotType',
446 'assertInstanceOf' => 'assertType',
447 'assertEmpty' => 'assertEmpty2',
450 if ( method_exists( $this->suite
, $func ) ) {
451 return call_user_func_array( array( $this->suite
, $func ), $args);
452 } elseif ( isset( $compatibility[$func] ) ) {
453 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
455 throw new MWException( "Called non-existant $func method on "
456 . get_class( $this ) );
460 private function assertEmpty2( $value, $msg ) {
461 return $this->assertTrue( $value == '', $msg );
464 static private function unprefixTable( $tableName ) {
466 return substr( $tableName, strlen( $wgDBprefix ) );
469 static private function isNotUnittest( $table ) {
470 return strpos( $table, 'unittest_' ) !== 0;
473 public static function listTables( $db ) {
476 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
477 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
479 // Don't duplicate test tables from the previous fataled run
480 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
482 if ( $db->getType() == 'sqlite' ) {
483 $tables = array_flip( $tables );
484 // these are subtables of searchindex and don't need to be duped/dropped separately
485 unset( $tables['searchindex_content'] );
486 unset( $tables['searchindex_segdir'] );
487 unset( $tables['searchindex_segments'] );
488 $tables = array_flip( $tables );
493 protected function checkDbIsSupported() {
494 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
495 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
499 public function getCliArg( $offset ) {
501 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
502 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
507 public function setCliArg( $offset, $value ) {
509 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
514 * Don't throw a warning if $function is deprecated and called later
516 * @param $function String
519 function hideDeprecated( $function ) {
520 wfSuppressWarnings();
521 wfDeprecated( $function );
526 * Asserts that the given database query yields the rows given by $expectedRows.
527 * The expected rows should be given as indexed (not associative) arrays, with
528 * the values given in the order of the columns in the $fields parameter.
529 * Note that the rows are sorted by the columns given in $fields.
533 * @param $table String|Array the table(s) to query
534 * @param $fields String|Array the columns to include in the result (and to sort by)
535 * @param $condition String|Array "where" condition(s)
536 * @param $expectedRows Array - an array of arrays giving the expected rows.
538 * @throws MWException if this test cases's needsDB() method doesn't return true.
539 * Test cases can use "@group Database" to enable database test support,
540 * or list the tables under testing in $this->tablesUsed, or override the
543 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
544 if ( !$this->needsDB() ) {
545 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
546 ' method should return true. Use @group Database or $this->tablesUsed.');
549 $db = wfGetDB( DB_SLAVE
);
551 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
552 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
556 foreach ( $expectedRows as $expected ) {
557 $r = $res->fetchRow();
558 self
::stripStringKeys( $r );
561 $this->assertNotEmpty( $r, "row #$i missing" );
563 $this->assertEquals( $expected, $r, "row #$i mismatches" );
566 $r = $res->fetchRow();
567 self
::stripStringKeys( $r );
569 $this->assertFalse( $r, "found extra row (after #$i)" );
573 * Utility method taking an array of elements and wrapping
574 * each element in it's own array. Useful for data providers
575 * that only return a single argument.
579 * @param array $elements
583 protected function arrayWrap( array $elements ) {
585 function( $element ) {
586 return array( $element );
593 * Assert that two arrays are equal. By default this means that both arrays need to hold
594 * the same set of values. Using additional arguments, order and associated key can also
595 * be set as relevant.
599 * @param array $expected
600 * @param array $actual
601 * @param boolean $ordered If the order of the values should match
602 * @param boolean $named If the keys should match
604 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
606 $this->objectAssociativeSort( $expected );
607 $this->objectAssociativeSort( $actual );
611 $expected = array_values( $expected );
612 $actual = array_values( $actual );
615 call_user_func_array(
616 array( $this, 'assertEquals' ),
617 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
622 * Put each HTML element on its own line and then equals() the results
624 * Use for nicely formatting of PHPUnit diff output when comparing very
629 * @param String $expected HTML on oneline
630 * @param String $actual HTML on oneline
631 * @param String $msg Optional message
633 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
634 $expected = str_replace( '>', ">\n", $expected );
635 $actual = str_replace( '>', ">\n", $actual );
637 $this->assertEquals( $expected, $actual, $msg );
641 * Does an associative sort that works for objects.
645 * @param array $array
647 protected function objectAssociativeSort( array &$array ) {
651 return serialize( $a ) > serialize( $b ) ?
1 : -1;
657 * Utility function for eliminating all string keys from an array.
658 * Useful to turn a database result row as returned by fetchRow() into
659 * a pure indexed array.
663 * @param $r mixed the array to remove string keys from.
665 protected static function stripStringKeys( &$r ) {
666 if ( !is_array( $r ) ) {
670 foreach ( $r as $k => $v ) {
671 if ( is_string( $k ) ) {
678 * Asserts that the provided variable is of the specified
679 * internal type or equals the $value argument. This is useful
680 * for testing return types of functions that return a certain
681 * type or *value* when not set or on error.
685 * @param string $type
686 * @param mixed $actual
687 * @param mixed $value
688 * @param string $message
690 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
691 if ( $actual === $value ) {
692 $this->assertTrue( true, $message );
695 $this->assertType( $type, $actual, $message );
700 * Asserts the type of the provided value. This can be either
701 * in internal type such as boolean or integer, or a class or
702 * interface the value extends or implements.
706 * @param string $type
707 * @param mixed $actual
708 * @param string $message
710 protected function assertType( $type, $actual, $message = '' ) {
711 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
712 $this->assertInstanceOf( $type, $actual, $message );
715 $this->assertInternalType( $type, $actual, $message );
720 * Returns true iff the given namespace defaults to Wikitext
721 * according to $wgNamespaceContentModels
723 * @param int $ns The namespace ID to check
728 protected function isWikitextNS( $ns ) {
729 global $wgNamespaceContentModels;
731 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
732 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
739 * Returns the ID of a namespace that defaults to Wikitext.
740 * Throws an MWException if there is none.
742 * @return int the ID of the wikitext Namespace
745 protected function getDefaultWikitextNS() {
746 global $wgNamespaceContentModels;
748 static $wikitextNS = null; // this is not going to change
749 if ( $wikitextNS !== null ) {
753 // quickly short out on most common case:
754 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
758 // NOTE: prefer content namespaces
759 $namespaces = array_unique( array_merge(
760 MWNamespace
::getContentNamespaces(),
761 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
762 MWNamespace
::getValidNamespaces()
765 $namespaces = array_diff( $namespaces, array(
766 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
769 $talk = array_filter( $namespaces, function ( $ns ) {
770 return MWNamespace
::isTalk( $ns );
773 // prefer non-talk pages
774 $namespaces = array_diff( $namespaces, $talk );
775 $namespaces = array_merge( $namespaces, $talk );
777 // check default content model of each namespace
778 foreach ( $namespaces as $ns ) {
779 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
780 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
) {
788 // @todo: Inside a test, we could skip the test as incomplete.
789 // But frequently, this is used in fixture setup.
790 throw new MWException( "No namespace defaults to wikitext!" );