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();
34 * Table name prefixes. Oracle likes it shorter.
36 const DB_PREFIX
= 'unittest_';
37 const ORA_DB_PREFIX
= 'ut_';
39 protected $supportedDBs = array(
46 function __construct( $name = null, array $data = array(), $dataName = '' ) {
47 parent
::__construct( $name, $data, $dataName );
49 $this->backupGlobals
= false;
50 $this->backupStaticAttributes
= false;
53 function run( PHPUnit_Framework_TestResult
$result = NULL ) {
54 /* Some functions require some kind of caching, and will end up using the db,
55 * which we can't allow, as that would open a new connection for mysql.
56 * Replace with a HashBag. They would not be going to persist anyway.
58 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
60 if( $this->needsDB() ) {
63 $this->useTemporaryTables
= !$this->getCliArg( 'use-normal-tables' );
64 $this->reuseDB
= $this->getCliArg('reuse-db');
66 $this->db
= wfGetDB( DB_MASTER
);
68 $this->checkDbIsSupported();
70 $this->oldTablePrefix
= $wgDBprefix;
72 if( !self
::$dbSetup ) {
74 self
::$dbSetup = true;
77 $this->addCoreDBData();
80 parent
::run( $result );
84 parent
::run( $result );
89 * obtains a new temporary file name
91 * The obtained filename is enlisted to be removed upon tearDown
93 * @returns string: absolute name of the temporary file
95 protected function getNewTempFile() {
96 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
97 $this->tmpfiles
[] = $fname;
102 * obtains a new temporary directory
104 * The obtained directory is enlisted to be removed (recursively with all its contained
105 * files) upon tearDown.
107 * @returns string: absolute name of the temporary directory
109 protected function getNewTempDirectory() {
110 // Starting of with a temporary /file/.
111 $fname = $this->getNewTempFile();
113 // Converting the temporary /file/ to a /directory/
115 // The following is not atomic, but at least we now have a single place,
116 // where temporary directory creation is bundled and can be improved
118 $this->assertTrue( wfMkdirParents( $fname ) );
122 protected function tearDown() {
123 // Cleaning up temporary files
124 foreach ( $this->tmpfiles
as $fname ) {
125 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
127 } elseif ( is_dir( $fname ) ) {
128 wfRecursiveRemoveDir( $fname );
132 // clean up open transactions
133 if( $this->needsDB() && $this->db
) {
134 while( $this->db
->trxLevel() > 0 ) {
135 $this->db
->rollback();
142 function dbPrefix() {
143 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
147 # if the test says it uses database tables, it needs the database
148 if ( $this->tablesUsed
) {
152 # if the test says it belongs to the Database group, it needs the database
153 $rc = new ReflectionClass( $this );
154 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
162 * Stub. If a test needs to add additional data to the database, it should
163 * implement this method and do so
165 function addDBData() {}
167 private function addCoreDBData() {
168 # disabled for performance
169 #$this->tablesUsed[] = 'page';
170 #$this->tablesUsed[] = 'revision';
172 if ( $this->db
->getType() == 'oracle' ) {
174 # Insert 0 user to prevent FK violations
176 $this->db
->insert( 'user', array(
178 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
180 # Insert 0 page to prevent FK violations
182 $this->db
->insert( 'page', array(
184 'page_namespace' => 0,
186 'page_restrictions' => NULL,
188 'page_is_redirect' => 0,
191 'page_touched' => $this->db
->timestamp(),
193 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
197 User
::resetIdByNameCache();
200 $user = User
::newFromName( 'UTSysop' );
202 if ( $user->idForName() == 0 ) {
203 $user->addToDatabase();
204 $user->setPassword( 'UTSysopPassword' );
206 $user->addGroup( 'sysop' );
207 $user->addGroup( 'bureaucrat' );
208 $user->saveSettings();
212 //Make 1 page with 1 revision
213 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
214 if ( !$page->getId() == 0 ) {
215 $page->doEdit( 'UTContent',
219 User
::newFromName( 'UTSysop' ) );
223 private function initDB() {
225 if ( $wgDBprefix === $this->dbPrefix() ) {
226 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
229 $tablesCloned = $this->listTables();
230 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
231 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
233 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
234 CloneDatabase
::changePrefix( $this->dbPrefix() );
238 $dbClone->cloneTableStructure();
241 if ( $this->db
->getType() == 'oracle' ) {
242 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
247 * Empty all tables so they can be repopulated for tests
249 private function resetDB() {
251 if ( $this->db
->getType() == 'oracle' ) {
252 if ( $this->useTemporaryTables
) {
253 wfGetLB()->closeAll();
254 $this->db
= wfGetDB( DB_MASTER
);
256 foreach( $this->tablesUsed
as $tbl ) {
257 if( $tbl == 'interwiki') continue;
258 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
262 foreach( $this->tablesUsed
as $tbl ) {
263 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
264 $this->db
->delete( $tbl, '*', __METHOD__
);
270 function __call( $func, $args ) {
271 static $compatibility = array(
272 'assertInternalType' => 'assertType',
273 'assertNotInternalType' => 'assertNotType',
274 'assertInstanceOf' => 'assertType',
275 'assertEmpty' => 'assertEmpty2',
278 if ( method_exists( $this->suite
, $func ) ) {
279 return call_user_func_array( array( $this->suite
, $func ), $args);
280 } elseif ( isset( $compatibility[$func] ) ) {
281 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
283 throw new MWException( "Called non-existant $func method on "
284 . get_class( $this ) );
288 private function assertEmpty2( $value, $msg ) {
289 return $this->assertTrue( $value == '', $msg );
292 static private function unprefixTable( $tableName ) {
294 return substr( $tableName, strlen( $wgDBprefix ) );
297 static private function isNotUnittest( $table ) {
298 return strpos( $table, 'unittest_' ) !== 0;
301 protected function listTables() {
304 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
305 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
307 // Don't duplicate test tables from the previous fataled run
308 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
310 if ( $this->db
->getType() == 'sqlite' ) {
311 $tables = array_flip( $tables );
312 // these are subtables of searchindex and don't need to be duped/dropped separately
313 unset( $tables['searchindex_content'] );
314 unset( $tables['searchindex_segdir'] );
315 unset( $tables['searchindex_segments'] );
316 $tables = array_flip( $tables );
321 protected function checkDbIsSupported() {
322 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
323 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
327 public function getCliArg( $offset ) {
329 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
330 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
335 public function setCliArg( $offset, $value ) {
337 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
342 * Don't throw a warning if $function is deprecated and called later
344 * @param $function String
347 function hideDeprecated( $function ) {
348 wfSuppressWarnings();
349 wfDeprecated( $function );
354 * Asserts that the given database query yields the rows given by $expectedRows.
355 * The expected rows should be given as indexed (not associative) arrays, with
356 * the values given in the order of the columns in the $fields parameter.
357 * Note that the rows are sorted by the columns given in $fields.
361 * @param $table String|Array the table(s) to query
362 * @param $fields String|Array the columns to include in the result (and to sort by)
363 * @param $condition String|Array "where" condition(s)
364 * @param $expectedRows Array - an array of arrays giving the expected rows.
366 * @throws MWException if this test cases's needsDB() method doesn't return true.
367 * Test cases can use "@group Database" to enable database test support,
368 * or list the tables under testing in $this->tablesUsed, or override the
371 protected function assertSelect( $table, $fields, $condition, Array $expectedRows ) {
372 if ( !$this->needsDB() ) {
373 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
374 ' method should return true. Use @group Database or $this->tablesUsed.');
377 $db = wfGetDB( DB_SLAVE
);
379 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
380 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
384 foreach ( $expectedRows as $expected ) {
385 $r = $res->fetchRow();
386 self
::stripStringKeys( $r );
389 $this->assertNotEmpty( $r, "row #$i missing" );
391 $this->assertEquals( $expected, $r, "row #$i mismatches" );
394 $r = $res->fetchRow();
395 self
::stripStringKeys( $r );
397 $this->assertFalse( $r, "found extra row (after #$i)" );
401 * Utility method taking an array of elements and wrapping
402 * each element in it's own array. Useful for data providers
403 * that only return a single argument.
407 * @param array $elements
411 protected function arrayWrap( array $elements ) {
413 function( $element ) {
414 return array( $element );
421 * Assert that two arrays are equal. By default this means that both arrays need to hold
422 * the same set of values. Using additional arguments, order and associated key can also
423 * be set as relevant.
427 * @param array $expected
428 * @param array $actual
429 * @param boolean $ordered If the order of the values should match
430 * @param boolean $named If the keys should match
432 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
434 $this->objectAssociativeSort( $expected );
435 $this->objectAssociativeSort( $actual );
439 $expected = array_values( $expected );
440 $actual = array_values( $actual );
443 call_user_func_array(
444 array( $this, 'assertEquals' ),
445 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
450 * Put each HTML element on its own line and then equals() the results
452 * Use for nicely formatting of PHPUnit diff output when comparing very
457 * @param String $expected HTML on oneline
458 * @param String $actual HTML on oneline
459 * @param String $msg Optional message
461 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
462 $expected = str_replace( '>', ">\n", $expected );
463 $actual = str_replace( '>', ">\n", $actual );
465 $this->assertEquals( $expected, $actual, $msg );
469 * Does an associative sort that works for objects.
473 * @param array $array
475 protected function objectAssociativeSort( array &$array ) {
479 return serialize( $a ) > serialize( $b ) ?
1 : -1;
485 * Utility function for eliminating all string keys from an array.
486 * Useful to turn a database result row as returned by fetchRow() into
487 * a pure indexed array.
491 * @param $r mixed the array to remove string keys from.
493 protected static function stripStringKeys( &$r ) {
494 if ( !is_array( $r ) ) {
498 foreach ( $r as $k => $v ) {
499 if ( is_string( $k ) ) {