3 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
6 public $runDisabled = false;
9 * @var Array of TestUser
17 protected $oldTablePrefix;
18 protected $useTemporaryTables = true;
19 protected $reuseDB = false;
20 protected $tablesUsed = array(); // tables with data
22 private static $dbSetup = 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() ) {
70 $this->useTemporaryTables
= !$this->getCliArg( 'use-normal-tables' );
71 $this->reuseDB
= $this->getCliArg('reuse-db');
73 $this->db
= wfGetDB( DB_MASTER
);
75 $this->checkDbIsSupported();
77 $this->oldTablePrefix
= $wgDBprefix;
79 if( !self
::$dbSetup ) {
81 self
::$dbSetup = true;
84 $this->addCoreDBData();
87 parent
::run( $result );
91 parent
::run( $result );
96 * obtains a new temporary file name
98 * The obtained filename is enlisted to be removed upon tearDown
100 * @returns string: absolute name of the temporary file
102 protected function getNewTempFile() {
103 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
104 $this->tmpfiles
[] = $fname;
109 * obtains a new temporary directory
111 * The obtained directory is enlisted to be removed (recursively with all its contained
112 * files) upon tearDown.
114 * @returns string: absolute name of the temporary directory
116 protected function getNewTempDirectory() {
117 // Starting of with a temporary /file/.
118 $fname = $this->getNewTempFile();
120 // Converting the temporary /file/ to a /directory/
122 // The following is not atomic, but at least we now have a single place,
123 // where temporary directory creation is bundled and can be improved
125 $this->assertTrue( wfMkdirParents( $fname ) );
130 * setUp and tearDown should (where significant)
131 * happen in reverse order.
133 protected function setUp() {
136 // Cleaning up temporary files
137 foreach ( $this->tmpfiles
as $fname ) {
138 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
140 } elseif ( is_dir( $fname ) ) {
141 wfRecursiveRemoveDir( $fname );
145 // Clean up open transactions
146 if ( $this->needsDB() && $this->db
) {
147 while( $this->db
->trxLevel() > 0 ) {
148 $this->db
->rollback();
153 protected function tearDown() {
154 // Cleaning up temporary files
155 foreach ( $this->tmpfiles
as $fname ) {
156 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
158 } elseif ( is_dir( $fname ) ) {
159 wfRecursiveRemoveDir( $fname );
163 // Clean up open transactions
164 if ( $this->needsDB() && $this->db
) {
165 while( $this->db
->trxLevel() > 0 ) {
166 $this->db
->rollback();
170 // Restore mw globals
171 foreach ( $this->mwGlobals
as $key => $value ) {
172 $GLOBALS[$key] = $value;
174 $this->mwGlobals
= array();
180 * Individual test functions may override globals (either directly or through this
181 * setMwGlobals() function), however one must call this method at least once for
182 * each key within the setUp().
183 * That way the key is added to the array of globals that will be reset afterwards
184 * in the tearDown(). And, equally important, that way all other tests are executed
185 * with the same settings (instead of using the unreliable local settings for most
186 * tests and fix it only for some tests).
190 * protected function setUp() {
191 * $this->setMwGlobals( 'wgRestrictStuff', true );
194 * function testFoo() {}
196 * function testBar() {}
197 * $this->assertTrue( self::getX()->doStuff() );
199 * $this->setMwGlobals( 'wgRestrictStuff', false );
200 * $this->assertTrue( self::getX()->doStuff() );
203 * function testQuux() {}
206 * @param array|string $pairs Key to the global variable, or an array
207 * of key/value pairs.
208 * @param mixed $value Value to set the global to (ignored
209 * if an array is given as first argument).
211 protected function setMwGlobals( $pairs, $value = null ) {
212 if ( !is_array( $pairs ) ) {
214 $this->mwGlobals
[$key] = $GLOBALS[$key];
215 $GLOBALS[$key] = $value;
217 foreach ( $pairs as $key => $value ) {
218 $this->mwGlobals
[$key] = $GLOBALS[$key];
219 $GLOBALS[$key] = $value;
224 function dbPrefix() {
225 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
229 # if the test says it uses database tables, it needs the database
230 if ( $this->tablesUsed
) {
234 # if the test says it belongs to the Database group, it needs the database
235 $rc = new ReflectionClass( $this );
236 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
244 * Stub. If a test needs to add additional data to the database, it should
245 * implement this method and do so
247 function addDBData() {}
249 private function addCoreDBData() {
250 # disabled for performance
251 #$this->tablesUsed[] = 'page';
252 #$this->tablesUsed[] = 'revision';
254 if ( $this->db
->getType() == 'oracle' ) {
256 # Insert 0 user to prevent FK violations
258 $this->db
->insert( 'user', array(
260 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
262 # Insert 0 page to prevent FK violations
264 $this->db
->insert( 'page', array(
266 'page_namespace' => 0,
268 'page_restrictions' => NULL,
270 'page_is_redirect' => 0,
273 'page_touched' => $this->db
->timestamp(),
275 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
279 User
::resetIdByNameCache();
282 $user = User
::newFromName( 'UTSysop' );
284 if ( $user->idForName() == 0 ) {
285 $user->addToDatabase();
286 $user->setPassword( 'UTSysopPassword' );
288 $user->addGroup( 'sysop' );
289 $user->addGroup( 'bureaucrat' );
290 $user->saveSettings();
294 //Make 1 page with 1 revision
295 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
296 if ( !$page->getId() == 0 ) {
297 $page->doEdit( 'UTContent',
301 User
::newFromName( 'UTSysop' ) );
305 private function initDB() {
307 if ( $wgDBprefix === $this->dbPrefix() ) {
308 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
311 $tablesCloned = $this->listTables();
312 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
313 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
315 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
316 CloneDatabase
::changePrefix( $this->dbPrefix() );
320 $dbClone->cloneTableStructure();
323 if ( $this->db
->getType() == 'oracle' ) {
324 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
329 * Empty all tables so they can be repopulated for tests
331 private function resetDB() {
333 if ( $this->db
->getType() == 'oracle' ) {
334 if ( $this->useTemporaryTables
) {
335 wfGetLB()->closeAll();
336 $this->db
= wfGetDB( DB_MASTER
);
338 foreach( $this->tablesUsed
as $tbl ) {
339 if( $tbl == 'interwiki') continue;
340 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
344 foreach( $this->tablesUsed
as $tbl ) {
345 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
346 $this->db
->delete( $tbl, '*', __METHOD__
);
352 function __call( $func, $args ) {
353 static $compatibility = array(
354 'assertInternalType' => 'assertType',
355 'assertNotInternalType' => 'assertNotType',
356 'assertInstanceOf' => 'assertType',
357 'assertEmpty' => 'assertEmpty2',
360 if ( method_exists( $this->suite
, $func ) ) {
361 return call_user_func_array( array( $this->suite
, $func ), $args);
362 } elseif ( isset( $compatibility[$func] ) ) {
363 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
365 throw new MWException( "Called non-existant $func method on "
366 . get_class( $this ) );
370 private function assertEmpty2( $value, $msg ) {
371 return $this->assertTrue( $value == '', $msg );
374 static private function unprefixTable( $tableName ) {
376 return substr( $tableName, strlen( $wgDBprefix ) );
379 static private function isNotUnittest( $table ) {
380 return strpos( $table, 'unittest_' ) !== 0;
383 protected function listTables() {
386 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
387 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
389 // Don't duplicate test tables from the previous fataled run
390 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
392 if ( $this->db
->getType() == 'sqlite' ) {
393 $tables = array_flip( $tables );
394 // these are subtables of searchindex and don't need to be duped/dropped separately
395 unset( $tables['searchindex_content'] );
396 unset( $tables['searchindex_segdir'] );
397 unset( $tables['searchindex_segments'] );
398 $tables = array_flip( $tables );
403 protected function checkDbIsSupported() {
404 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
405 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
409 public function getCliArg( $offset ) {
411 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
412 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
417 public function setCliArg( $offset, $value ) {
419 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
424 * Don't throw a warning if $function is deprecated and called later
426 * @param $function String
429 function hideDeprecated( $function ) {
430 wfSuppressWarnings();
431 wfDeprecated( $function );
436 * Asserts that the given database query yields the rows given by $expectedRows.
437 * The expected rows should be given as indexed (not associative) arrays, with
438 * the values given in the order of the columns in the $fields parameter.
439 * Note that the rows are sorted by the columns given in $fields.
443 * @param $table String|Array the table(s) to query
444 * @param $fields String|Array the columns to include in the result (and to sort by)
445 * @param $condition String|Array "where" condition(s)
446 * @param $expectedRows Array - an array of arrays giving the expected rows.
448 * @throws MWException if this test cases's needsDB() method doesn't return true.
449 * Test cases can use "@group Database" to enable database test support,
450 * or list the tables under testing in $this->tablesUsed, or override the
453 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
454 if ( !$this->needsDB() ) {
455 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
456 ' method should return true. Use @group Database or $this->tablesUsed.');
459 $db = wfGetDB( DB_SLAVE
);
461 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
462 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
466 foreach ( $expectedRows as $expected ) {
467 $r = $res->fetchRow();
468 self
::stripStringKeys( $r );
471 $this->assertNotEmpty( $r, "row #$i missing" );
473 $this->assertEquals( $expected, $r, "row #$i mismatches" );
476 $r = $res->fetchRow();
477 self
::stripStringKeys( $r );
479 $this->assertFalse( $r, "found extra row (after #$i)" );
483 * Utility method taking an array of elements and wrapping
484 * each element in it's own array. Useful for data providers
485 * that only return a single argument.
489 * @param array $elements
493 protected function arrayWrap( array $elements ) {
495 function( $element ) {
496 return array( $element );
503 * Assert that two arrays are equal. By default this means that both arrays need to hold
504 * the same set of values. Using additional arguments, order and associated key can also
505 * be set as relevant.
509 * @param array $expected
510 * @param array $actual
511 * @param boolean $ordered If the order of the values should match
512 * @param boolean $named If the keys should match
514 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
516 $this->objectAssociativeSort( $expected );
517 $this->objectAssociativeSort( $actual );
521 $expected = array_values( $expected );
522 $actual = array_values( $actual );
525 call_user_func_array(
526 array( $this, 'assertEquals' ),
527 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
532 * Put each HTML element on its own line and then equals() the results
534 * Use for nicely formatting of PHPUnit diff output when comparing very
539 * @param String $expected HTML on oneline
540 * @param String $actual HTML on oneline
541 * @param String $msg Optional message
543 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
544 $expected = str_replace( '>', ">\n", $expected );
545 $actual = str_replace( '>', ">\n", $actual );
547 $this->assertEquals( $expected, $actual, $msg );
551 * Does an associative sort that works for objects.
555 * @param array $array
557 protected function objectAssociativeSort( array &$array ) {
561 return serialize( $a ) > serialize( $b ) ?
1 : -1;
567 * Utility function for eliminating all string keys from an array.
568 * Useful to turn a database result row as returned by fetchRow() into
569 * a pure indexed array.
573 * @param $r mixed the array to remove string keys from.
575 protected static function stripStringKeys( &$r ) {
576 if ( !is_array( $r ) ) {
580 foreach ( $r as $k => $v ) {
581 if ( is_string( $k ) ) {
588 * Asserts that the provided variable is of the specified
589 * internal type or equals the $value argument. This is useful
590 * for testing return types of functions that return a certain
591 * type or *value* when not set or on error.
595 * @param string $type
596 * @param mixed $actual
597 * @param mixed $value
598 * @param string $message
600 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
601 if ( $actual === $value ) {
602 $this->assertTrue( true, $message );
605 $this->assertType( $type, $actual, $message );
610 * Asserts the type of the provided value. This can be either
611 * in internal type such as boolean or integer, or a class or
612 * interface the value extends or implements.
616 * @param string $type
617 * @param mixed $actual
618 * @param string $message
620 protected function assertType( $type, $actual, $message = '' ) {
621 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
622 $this->assertInstanceOf( $type, $actual, $message );
625 $this->assertInternalType( $type, $actual, $message );