3 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
6 public $runDisabled = false;
12 protected $oldTablePrefix;
13 protected $useTemporaryTables = true;
14 protected $reuseDB = false;
15 protected $tablesUsed = array(); // tables with data
17 protected $restoreGlobals = array( // global variables to restore for each test
25 private $savedGlobals = array();
27 private static $dbSetup = false;
30 * Holds the paths of temporary files/directories created through getNewTempFile,
31 * and getNewTempDirectory
35 private $tmpfiles = array();
39 * Table name prefixes. Oracle likes it shorter.
41 const DB_PREFIX
= 'unittest_';
42 const ORA_DB_PREFIX
= 'ut_';
44 protected $supportedDBs = array(
51 function __construct( $name = null, array $data = array(), $dataName = '' ) {
52 parent
::__construct( $name, $data, $dataName );
54 $this->backupGlobals
= false;
55 $this->backupStaticAttributes
= false;
58 function run( PHPUnit_Framework_TestResult
$result = NULL ) {
59 /* Some functions require some kind of caching, and will end up using the db,
60 * which we can't allow, as that would open a new connection for mysql.
61 * Replace with a HashBag. They would not be going to persist anyway.
63 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
65 if( $this->needsDB() ) {
68 $this->useTemporaryTables
= !$this->getCliArg( 'use-normal-tables' );
69 $this->reuseDB
= $this->getCliArg('reuse-db');
71 $this->db
= wfGetDB( DB_MASTER
);
73 $this->checkDbIsSupported();
75 $this->oldTablePrefix
= $wgDBprefix;
77 if( !self
::$dbSetup ) {
79 self
::$dbSetup = true;
82 $this->addCoreDBData();
85 parent
::run( $result );
89 parent
::run( $result );
94 * obtains a new temporary file name
96 * The obtained filename is enlisted to be removed upon tearDown
98 * @returns string: absolute name of the temporary file
100 protected function getNewTempFile() {
101 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
102 $this->tmpfiles
[] = $fname;
107 * obtains a new temporary directory
109 * The obtained directory is enlisted to be removed (recursively with all its contained
110 * files) upon tearDown.
112 * @returns string: absolute name of the temporary directory
114 protected function getNewTempDirectory() {
115 // Starting of with a temporary /file/.
116 $fname = $this->getNewTempFile();
118 // Converting the temporary /file/ to a /directory/
120 // The following is not atomic, but at least we now have a single place,
121 // where temporary directory creation is bundled and can be improved
123 $this->assertTrue( wfMkdirParents( $fname ) );
127 protected function setup() {
130 foreach ( $this->restoreGlobals
as $var ) {
131 $v = $GLOBALS[ $var ];
133 if ( is_object( $v ) ||
is_array( $v ) ) {
137 $this->savedGlobals
[ $var ] = $v;
141 protected function teardown() {
142 // Cleaning up temporary files
143 foreach ( $this->tmpfiles
as $fname ) {
144 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
146 } elseif ( is_dir( $fname ) ) {
147 wfRecursiveRemoveDir( $fname );
151 // clean up open transactions
152 if( $this->needsDB() && $this->db
) {
153 while( $this->db
->trxLevel() > 0 ) {
154 $this->db
->rollback();
158 // restore saved globals
159 foreach ( $this->savedGlobals
as $k => $v ) {
166 function dbPrefix() {
167 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
171 # if the test says it uses database tables, it needs the database
172 if ( $this->tablesUsed
) {
176 # if the test says it belongs to the Database group, it needs the database
177 $rc = new ReflectionClass( $this );
178 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
186 * Stub. If a test needs to add additional data to the database, it should
187 * implement this method and do so
189 function addDBData() {}
191 private function addCoreDBData() {
192 # disabled for performance
193 #$this->tablesUsed[] = 'page';
194 #$this->tablesUsed[] = 'revision';
196 if ( $this->db
->getType() == 'oracle' ) {
198 # Insert 0 user to prevent FK violations
200 $this->db
->insert( 'user', array(
202 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
204 # Insert 0 page to prevent FK violations
206 $this->db
->insert( 'page', array(
208 'page_namespace' => 0,
210 'page_restrictions' => NULL,
212 'page_is_redirect' => 0,
215 'page_touched' => $this->db
->timestamp(),
217 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
221 User
::resetIdByNameCache();
224 $user = User
::newFromName( 'UTSysop' );
226 if ( $user->idForName() == 0 ) {
227 $user->addToDatabase();
228 $user->setPassword( 'UTSysopPassword' );
230 $user->addGroup( 'sysop' );
231 $user->addGroup( 'bureaucrat' );
232 $user->saveSettings();
236 //Make 1 page with 1 revision
237 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
238 if ( !$page->getId() == 0 ) {
239 $page->doEditContent(
240 new WikitextContent( 'UTContent' ),
244 User
::newFromName( 'UTSysop' ) );
248 private function initDB() {
250 if ( $wgDBprefix === $this->dbPrefix() ) {
251 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
254 $tablesCloned = $this->listTables();
255 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
256 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
258 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
259 CloneDatabase
::changePrefix( $this->dbPrefix() );
263 $dbClone->cloneTableStructure();
266 if ( $this->db
->getType() == 'oracle' ) {
267 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
272 * Empty all tables so they can be repopulated for tests
274 private function resetDB() {
276 if ( $this->db
->getType() == 'oracle' ) {
277 if ( $this->useTemporaryTables
) {
278 wfGetLB()->closeAll();
279 $this->db
= wfGetDB( DB_MASTER
);
281 foreach( $this->tablesUsed
as $tbl ) {
282 if( $tbl == 'interwiki') continue;
283 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
287 foreach( $this->tablesUsed
as $tbl ) {
288 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
289 $this->db
->delete( $tbl, '*', __METHOD__
);
295 function __call( $func, $args ) {
296 static $compatibility = array(
297 'assertInternalType' => 'assertType',
298 'assertNotInternalType' => 'assertNotType',
299 'assertInstanceOf' => 'assertType',
300 'assertEmpty' => 'assertEmpty2',
303 if ( method_exists( $this->suite
, $func ) ) {
304 return call_user_func_array( array( $this->suite
, $func ), $args);
305 } elseif ( isset( $compatibility[$func] ) ) {
306 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
308 throw new MWException( "Called non-existant $func method on "
309 . get_class( $this ) );
313 private function assertEmpty2( $value, $msg ) {
314 return $this->assertTrue( $value == '', $msg );
317 static private function unprefixTable( $tableName ) {
319 return substr( $tableName, strlen( $wgDBprefix ) );
322 static private function isNotUnittest( $table ) {
323 return strpos( $table, 'unittest_' ) !== 0;
326 protected function listTables() {
329 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
330 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
332 // Don't duplicate test tables from the previous fataled run
333 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
335 if ( $this->db
->getType() == 'sqlite' ) {
336 $tables = array_flip( $tables );
337 // these are subtables of searchindex and don't need to be duped/dropped separately
338 unset( $tables['searchindex_content'] );
339 unset( $tables['searchindex_segdir'] );
340 unset( $tables['searchindex_segments'] );
341 $tables = array_flip( $tables );
346 protected function checkDbIsSupported() {
347 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
348 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
352 public function getCliArg( $offset ) {
354 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
355 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
360 public function setCliArg( $offset, $value ) {
362 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
367 * Don't throw a warning if $function is deprecated and called later
369 * @param $function String
372 function hideDeprecated( $function ) {
373 wfSuppressWarnings();
374 wfDeprecated( $function );
379 * Asserts that the given database query yields the rows given by $expectedRows.
380 * The expected rows should be given as indexed (not associative) arrays, with
381 * the values given in the order of the columns in the $fields parameter.
382 * Note that the rows are sorted by the columns given in $fields.
386 * @param $table String|Array the table(s) to query
387 * @param $fields String|Array the columns to include in the result (and to sort by)
388 * @param $condition String|Array "where" condition(s)
389 * @param $expectedRows Array - an array of arrays giving the expected rows.
391 * @throws MWException if this test cases's needsDB() method doesn't return true.
392 * Test cases can use "@group Database" to enable database test support,
393 * or list the tables under testing in $this->tablesUsed, or override the
396 protected function assertSelect( $table, $fields, $condition, Array $expectedRows ) {
397 if ( !$this->needsDB() ) {
398 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
399 ' method should return true. Use @group Database or $this->tablesUsed.');
402 $db = wfGetDB( DB_SLAVE
);
404 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
405 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
409 foreach ( $expectedRows as $expected ) {
410 $r = $res->fetchRow();
411 self
::stripStringKeys( $r );
414 $this->assertNotEmpty( $r, "row #$i missing" );
416 $this->assertEquals( $expected, $r, "row #$i mismatches" );
419 $r = $res->fetchRow();
420 self
::stripStringKeys( $r );
422 $this->assertFalse( $r, "found extra row (after #$i)" );
426 * Utility method taking an array of elements and wrapping
427 * each element in it's own array. Useful for data providers
428 * that only return a single argument.
432 * @param array $elements
436 protected function arrayWrap( array $elements ) {
438 function( $element ) {
439 return array( $element );
446 * Assert that two arrays are equal. By default this means that both arrays need to hold
447 * the same set of values. Using additional arguments, order and associated key can also
448 * be set as relevant.
452 * @param array $expected
453 * @param array $actual
454 * @param boolean $ordered If the order of the values should match
455 * @param boolean $named If the keys should match
457 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
459 $this->objectAssociativeSort( $expected );
460 $this->objectAssociativeSort( $actual );
464 $expected = array_values( $expected );
465 $actual = array_values( $actual );
468 call_user_func_array(
469 array( $this, 'assertEquals' ),
470 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
475 * Put each HTML element on its own line and then equals() the results
477 * Use for nicely formatting of PHPUnit diff output when comparing very
482 * @param String $expected HTML on oneline
483 * @param String $actual HTML on oneline
484 * @param String $msg Optional message
486 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
487 $expected = str_replace( '>', ">\n", $expected );
488 $actual = str_replace( '>', ">\n", $actual );
490 $this->assertEquals( $expected, $actual, $msg );
494 * Does an associative sort that works for objects.
498 * @param array $array
500 protected function objectAssociativeSort( array &$array ) {
504 return serialize( $a ) > serialize( $b ) ?
1 : -1;
510 * Utility function for eliminating all string keys from an array.
511 * Useful to turn a database result row as returned by fetchRow() into
512 * a pure indexed array.
516 * @param $r mixed the array to remove string keys from.
518 protected static function stripStringKeys( &$r ) {
519 if ( !is_array( $r ) ) {
523 foreach ( $r as $k => $v ) {
524 if ( is_string( $k ) ) {