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 temoporary files
119 foreach ( $this->tmpfiles
as $fname ) {
120 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
122 } elseif ( is_dir( $fname ) ) {
123 wfRecursiveRemoveDir( $fname );
130 function dbPrefix() {
131 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
135 # if the test says it uses database tables, it needs the database
136 if ( $this->tablesUsed
) {
140 # if the test says it belongs to the Database group, it needs the database
141 $rc = new ReflectionClass( $this );
142 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
150 * Stub. If a test needs to add additional data to the database, it should
151 * implement this method and do so
153 function addDBData() {}
155 private function addCoreDBData() {
156 # disabled for performance
157 #$this->tablesUsed[] = 'page';
158 #$this->tablesUsed[] = 'revision';
160 if ( $this->db
->getType() == 'oracle' ) {
162 # Insert 0 user to prevent FK violations
164 $this->db
->insert( 'user', array(
166 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
168 # Insert 0 page to prevent FK violations
170 $this->db
->insert( 'page', array(
172 'page_namespace' => 0,
174 'page_restrictions' => NULL,
176 'page_is_redirect' => 0,
179 'page_touched' => $this->db
->timestamp(),
181 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
185 User
::resetIdByNameCache();
188 $user = User
::newFromName( 'UTSysop' );
190 if ( $user->idForName() == 0 ) {
191 $user->addToDatabase();
192 $user->setPassword( 'UTSysopPassword' );
194 $user->addGroup( 'sysop' );
195 $user->addGroup( 'bureaucrat' );
196 $user->saveSettings();
200 //Make 1 page with 1 revision
201 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
202 if ( !$page->getId() == 0 ) {
203 $page->doEdit( 'UTContent',
207 User
::newFromName( 'UTSysop' ) );
211 private function initDB() {
213 if ( $wgDBprefix === $this->dbPrefix() ) {
214 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
217 $tablesCloned = $this->listTables();
218 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
219 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
221 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
222 CloneDatabase
::changePrefix( $this->dbPrefix() );
226 $dbClone->cloneTableStructure();
229 if ( $this->db
->getType() == 'oracle' ) {
230 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
235 * Empty all tables so they can be repopulated for tests
237 private function resetDB() {
239 if ( $this->db
->getType() == 'oracle' ) {
240 if ( $this->useTemporaryTables
) {
241 wfGetLB()->closeAll();
242 $this->db
= wfGetDB( DB_MASTER
);
244 foreach( $this->tablesUsed
as $tbl ) {
245 if( $tbl == 'interwiki') continue;
246 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
250 foreach( $this->tablesUsed
as $tbl ) {
251 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
252 $this->db
->delete( $tbl, '*', __METHOD__
);
258 function __call( $func, $args ) {
259 static $compatibility = array(
260 'assertInternalType' => 'assertType',
261 'assertNotInternalType' => 'assertNotType',
262 'assertInstanceOf' => 'assertType',
263 'assertEmpty' => 'assertEmpty2',
266 if ( method_exists( $this->suite
, $func ) ) {
267 return call_user_func_array( array( $this->suite
, $func ), $args);
268 } elseif ( isset( $compatibility[$func] ) ) {
269 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
271 throw new MWException( "Called non-existant $func method on "
272 . get_class( $this ) );
276 private function assertEmpty2( $value, $msg ) {
277 return $this->assertTrue( $value == '', $msg );
280 static private function unprefixTable( $tableName ) {
282 return substr( $tableName, strlen( $wgDBprefix ) );
285 static private function isNotUnittest( $table ) {
286 return strpos( $table, 'unittest_' ) !== 0;
289 protected function listTables() {
292 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
293 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
295 // Don't duplicate test tables from the previous fataled run
296 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
298 if ( $this->db
->getType() == 'sqlite' ) {
299 $tables = array_flip( $tables );
300 // these are subtables of searchindex and don't need to be duped/dropped separately
301 unset( $tables['searchindex_content'] );
302 unset( $tables['searchindex_segdir'] );
303 unset( $tables['searchindex_segments'] );
304 $tables = array_flip( $tables );
309 protected function checkDbIsSupported() {
310 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
311 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
315 public function getCliArg( $offset ) {
317 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
318 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
323 public function setCliArg( $offset, $value ) {
325 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
329 public static function disableInterwikis( $prefix, &$data ) {
334 * Don't throw a warning if $function is deprecated and called later
336 * @param $function String
339 function hideDeprecated( $function ) {
340 wfSuppressWarnings();
341 wfDeprecated( $function );
346 * Asserts that the given database query yields the rows given by $expectedRows.
347 * The expected rows should be given as indexed (not associative) arrays, with
348 * the values given in the order of the columns in the $fields parameter.
349 * Note that the rows are sorted by the columns given in $fields.
351 * @param $table String|Array the table(s) to query
352 * @param $fields String|Array the columns to include in the result (and to sort by)
353 * @param $condition String|Array "where" condition(s)
354 * @param $expectedRows Array - an array of arrays giving the expected rows.
356 * @throws MWException if this test cases's needsDB() method doesn't return true.
357 * Test cases can use "@group Database" to enable database test support,
358 * or list the tables under testing in $this->tablesUsed, or override the
361 protected function assertSelect( $table, $fields, $condition, Array $expectedRows ) {
362 if ( !$this->needsDB() ) {
363 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
364 ' method should return true. Use @group Database or $this->tablesUsed.');
367 $db = wfGetDB( DB_SLAVE
);
369 $res = $db->select( $table, $fields, $condition, array( 'ORDER BY' => $fields ) );
370 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
374 foreach ( $expectedRows as $expected ) {
375 $r = $res->fetchRow();
376 self
::stripStringKeys( $r );
379 $this->assertNotEmpty( $r, "row #$i missing" );
381 $this->assertEquals( $expected, $r, "row #$i mismatches" );
384 $r = $res->fetchRow();
385 self
::stripStringKeys( $r );
387 $this->assertFalse( $r, "found extra row (after #$i)" );
391 * Utility function for eliminating all string keys from an array.
392 * Useful to turn a database result row as returned by fetchRow() into
393 * a pure indexed array.
396 * @param $r mixed the array to remove string keys from.
398 protected static function stripStringKeys( &$r ) {
399 if ( !is_array( $r ) ) return;
401 foreach ( $r as $k => $v ) {
402 if ( is_string( $k ) ) unset( $r[$k] );