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 private static $dbSetup = false;
20 * Holds the paths of temporary files/directories created through getNewTempFile,
21 * and getNewTempDirectory
25 private $tmpfiles = array();
29 * Table name prefixes. Oracle likes it shorter.
31 const DB_PREFIX
= 'unittest_';
32 const ORA_DB_PREFIX
= 'ut_';
34 protected $supportedDBs = array(
41 function __construct( $name = null, array $data = array(), $dataName = '' ) {
42 parent
::__construct( $name, $data, $dataName );
44 $this->backupGlobals
= false;
45 $this->backupStaticAttributes
= false;
48 function run( PHPUnit_Framework_TestResult
$result = NULL ) {
49 /* Some functions require some kind of caching, and will end up using the db,
50 * which we can't allow, as that would open a new connection for mysql.
51 * Replace with a HashBag. They would not be going to persist anyway.
53 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
55 if( $this->needsDB() ) {
58 $this->useTemporaryTables
= !$this->getCliArg( 'use-normal-tables' );
59 $this->reuseDB
= $this->getCliArg('reuse-db');
61 $this->db
= wfGetDB( DB_MASTER
);
63 $this->checkDbIsSupported();
65 $this->oldTablePrefix
= $wgDBprefix;
67 if( !self
::$dbSetup ) {
69 self
::$dbSetup = true;
72 $this->addCoreDBData();
75 parent
::run( $result );
79 parent
::run( $result );
84 * obtains a new temporary file name
86 * The obtained filename is enlisted to be removed upon tearDown
88 * @returns string: absolute name of the temporary file
90 protected function getNewTempFile() {
91 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
92 $this->tmpfiles
[] = $fname;
97 * obtains a new temporary directory
99 * The obtained directory is enlisted to be removed (recursively with all its contained
100 * files) upon tearDown.
102 * @returns string: absolute name of the temporary directory
104 protected function getNewTempDirectory() {
105 // Starting of with a temporary /file/.
106 $fname = $this->getNewTempFile();
108 // Converting the temporary /file/ to a /directory/
110 // The following is not atomic, but at least we now have a single place,
111 // where temporary directory creation is bundled and can be improved
113 $this->assertTrue( wfMkdirParents( $fname ) );
117 protected function tearDown() {
118 // Cleaning up temporary files
119 foreach ( $this->tmpfiles
as $fname ) {
120 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
122 } elseif ( is_dir( $fname ) ) {
123 wfRecursiveRemoveDir( $fname );
127 // clean up open transactions
128 if( $this->needsDB() && $this->db
) {
129 while( $this->db
->trxLevel() > 0 ) {
130 $this->db
->rollback();
137 function dbPrefix() {
138 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
142 # if the test says it uses database tables, it needs the database
143 if ( $this->tablesUsed
) {
147 # if the test says it belongs to the Database group, it needs the database
148 $rc = new ReflectionClass( $this );
149 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
157 * Stub. If a test needs to add additional data to the database, it should
158 * implement this method and do so
160 function addDBData() {}
162 private function addCoreDBData() {
163 # disabled for performance
164 #$this->tablesUsed[] = 'page';
165 #$this->tablesUsed[] = 'revision';
167 if ( $this->db
->getType() == 'oracle' ) {
169 # Insert 0 user to prevent FK violations
171 $this->db
->insert( 'user', array(
173 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
175 # Insert 0 page to prevent FK violations
177 $this->db
->insert( 'page', array(
179 'page_namespace' => 0,
181 'page_restrictions' => NULL,
183 'page_is_redirect' => 0,
186 'page_touched' => $this->db
->timestamp(),
188 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
192 User
::resetIdByNameCache();
195 $user = User
::newFromName( 'UTSysop' );
197 if ( $user->idForName() == 0 ) {
198 $user->addToDatabase();
199 $user->setPassword( 'UTSysopPassword' );
201 $user->addGroup( 'sysop' );
202 $user->addGroup( 'bureaucrat' );
203 $user->saveSettings();
207 //Make 1 page with 1 revision
208 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
209 if ( !$page->getId() == 0 ) {
210 $page->doEdit( 'UTContent',
214 User
::newFromName( 'UTSysop' ) );
218 private function initDB() {
220 if ( $wgDBprefix === $this->dbPrefix() ) {
221 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
224 $tablesCloned = $this->listTables();
225 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
226 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
228 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
229 CloneDatabase
::changePrefix( $this->dbPrefix() );
233 $dbClone->cloneTableStructure();
236 if ( $this->db
->getType() == 'oracle' ) {
237 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
242 * Empty all tables so they can be repopulated for tests
244 private function resetDB() {
246 if ( $this->db
->getType() == 'oracle' ) {
247 if ( $this->useTemporaryTables
) {
248 wfGetLB()->closeAll();
249 $this->db
= wfGetDB( DB_MASTER
);
251 foreach( $this->tablesUsed
as $tbl ) {
252 if( $tbl == 'interwiki') continue;
253 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
257 foreach( $this->tablesUsed
as $tbl ) {
258 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
259 $this->db
->delete( $tbl, '*', __METHOD__
);
265 function __call( $func, $args ) {
266 static $compatibility = array(
267 'assertInternalType' => 'assertType',
268 'assertNotInternalType' => 'assertNotType',
269 'assertInstanceOf' => 'assertType',
270 'assertEmpty' => 'assertEmpty2',
273 if ( method_exists( $this->suite
, $func ) ) {
274 return call_user_func_array( array( $this->suite
, $func ), $args);
275 } elseif ( isset( $compatibility[$func] ) ) {
276 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
278 throw new MWException( "Called non-existant $func method on "
279 . get_class( $this ) );
283 private function assertEmpty2( $value, $msg ) {
284 return $this->assertTrue( $value == '', $msg );
287 static private function unprefixTable( $tableName ) {
289 return substr( $tableName, strlen( $wgDBprefix ) );
292 static private function isNotUnittest( $table ) {
293 return strpos( $table, 'unittest_' ) !== 0;
296 protected function listTables() {
299 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
300 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
302 // Don't duplicate test tables from the previous fataled run
303 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
305 if ( $this->db
->getType() == 'sqlite' ) {
306 $tables = array_flip( $tables );
307 // these are subtables of searchindex and don't need to be duped/dropped separately
308 unset( $tables['searchindex_content'] );
309 unset( $tables['searchindex_segdir'] );
310 unset( $tables['searchindex_segments'] );
311 $tables = array_flip( $tables );
316 protected function checkDbIsSupported() {
317 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
318 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
322 public function getCliArg( $offset ) {
324 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
325 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
330 public function setCliArg( $offset, $value ) {
332 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
337 * Don't throw a warning if $function is deprecated and called later
339 * @param $function String
342 function hideDeprecated( $function ) {
343 wfSuppressWarnings();
344 wfDeprecated( $function );
349 * Asserts that the given database query yields the rows given by $expectedRows.
350 * The expected rows should be given as indexed (not associative) arrays, with
351 * the values given in the order of the columns in the $fields parameter.
352 * Note that the rows are sorted by the columns given in $fields.
356 * @param $table String|Array the table(s) to query
357 * @param $fields String|Array the columns to include in the result (and to sort by)
358 * @param $condition String|Array "where" condition(s)
359 * @param $expectedRows Array - an array of arrays giving the expected rows.
361 * @throws MWException if this test cases's needsDB() method doesn't return true.
362 * Test cases can use "@group Database" to enable database test support,
363 * or list the tables under testing in $this->tablesUsed, or override the
366 protected function assertSelect( $table, $fields, $condition, Array $expectedRows ) {
367 if ( !$this->needsDB() ) {
368 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
369 ' method should return true. Use @group Database or $this->tablesUsed.');
372 $db = wfGetDB( DB_SLAVE
);
374 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
375 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
379 foreach ( $expectedRows as $expected ) {
380 $r = $res->fetchRow();
381 self
::stripStringKeys( $r );
384 $this->assertNotEmpty( $r, "row #$i missing" );
386 $this->assertEquals( $expected, $r, "row #$i mismatches" );
389 $r = $res->fetchRow();
390 self
::stripStringKeys( $r );
392 $this->assertFalse( $r, "found extra row (after #$i)" );
396 * Utility method taking an array of elements and wrapping
397 * each element in it's own array. Useful for data providers
398 * that only return a single argument.
402 * @param array $elements
406 protected function arrayWrap( array $elements ) {
408 function( $element ) {
409 return array( $element );
416 * Assert that two arrays are equal. By default this means that both arrays need to hold
417 * the same set of values. Using additional arguments, order and associated key can also
418 * be set as relevant.
422 * @param array $expected
423 * @param array $actual
424 * @param boolean $ordered If the order of the values should match
425 * @param boolean $named If the keys should match
427 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
429 $this->objectAssociativeSort( $expected );
430 $this->objectAssociativeSort( $actual );
434 $expected = array_values( $expected );
435 $actual = array_values( $actual );
438 call_user_func_array(
439 array( $this, 'assertEquals' ),
440 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
445 * Does an associative sort that works for objects.
449 * @param array $array
451 protected function objectAssociativeSort( array &$array ) {
455 return serialize( $a ) > serialize( $b ) ?
1 : -1;
461 * Utility function for eliminating all string keys from an array.
462 * Useful to turn a database result row as returned by fetchRow() into
463 * a pure indexed array.
467 * @param $r mixed the array to remove string keys from.
469 protected static function stripStringKeys( &$r ) {
470 if ( !is_array( $r ) ) {
474 foreach ( $r as $k => $v ) {
475 if ( is_string( $k ) ) {