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 protected $restoreGlobals = array( // global variables to restore for each test
30 private $savedGlobals = array();
32 private static $dbSetup = false;
35 * Holds the paths of temporary files/directories created through getNewTempFile,
36 * and getNewTempDirectory
40 private $tmpfiles = array();
44 * Table name prefixes. Oracle likes it shorter.
46 const DB_PREFIX
= 'unittest_';
47 const ORA_DB_PREFIX
= 'ut_';
49 protected $supportedDBs = array(
56 function __construct( $name = null, array $data = array(), $dataName = '' ) {
57 parent
::__construct( $name, $data, $dataName );
59 $this->backupGlobals
= false;
60 $this->backupStaticAttributes
= false;
63 function run( PHPUnit_Framework_TestResult
$result = NULL ) {
64 /* Some functions require some kind of caching, and will end up using the db,
65 * which we can't allow, as that would open a new connection for mysql.
66 * Replace with a HashBag. They would not be going to persist anyway.
68 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
70 if( $this->needsDB() ) {
73 $this->useTemporaryTables
= !$this->getCliArg( 'use-normal-tables' );
74 $this->reuseDB
= $this->getCliArg('reuse-db');
76 $this->db
= wfGetDB( DB_MASTER
);
78 $this->checkDbIsSupported();
80 $this->oldTablePrefix
= $wgDBprefix;
82 if( !self
::$dbSetup ) {
84 self
::$dbSetup = true;
87 $this->addCoreDBData();
90 parent
::run( $result );
94 parent
::run( $result );
99 * obtains a new temporary file name
101 * The obtained filename is enlisted to be removed upon tearDown
103 * @returns string: absolute name of the temporary file
105 protected function getNewTempFile() {
106 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
107 $this->tmpfiles
[] = $fname;
112 * obtains a new temporary directory
114 * The obtained directory is enlisted to be removed (recursively with all its contained
115 * files) upon tearDown.
117 * @returns string: absolute name of the temporary directory
119 protected function getNewTempDirectory() {
120 // Starting of with a temporary /file/.
121 $fname = $this->getNewTempFile();
123 // Converting the temporary /file/ to a /directory/
125 // The following is not atomic, but at least we now have a single place,
126 // where temporary directory creation is bundled and can be improved
128 $this->assertTrue( wfMkdirParents( $fname ) );
132 protected function setup() {
135 foreach ( $this->restoreGlobals
as $var ) {
136 $v = $GLOBALS[ $var ];
138 if ( is_object( $v ) ) {
142 $this->savedGlobals
[$var] = $v;
146 protected function teardown() {
147 // Cleaning up temporary files
148 foreach ( $this->tmpfiles
as $fname ) {
149 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
151 } elseif ( is_dir( $fname ) ) {
152 wfRecursiveRemoveDir( $fname );
156 // clean up open transactions
157 if( $this->needsDB() && $this->db
) {
158 while( $this->db
->trxLevel() > 0 ) {
159 $this->db
->rollback();
163 // restore saved globals
164 foreach ( $this->savedGlobals
as $k => $v ) {
171 function dbPrefix() {
172 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
176 # if the test says it uses database tables, it needs the database
177 if ( $this->tablesUsed
) {
181 # if the test says it belongs to the Database group, it needs the database
182 $rc = new ReflectionClass( $this );
183 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
191 * Stub. If a test needs to add additional data to the database, it should
192 * implement this method and do so
194 function addDBData() {}
196 private function addCoreDBData() {
197 # disabled for performance
198 #$this->tablesUsed[] = 'page';
199 #$this->tablesUsed[] = 'revision';
201 if ( $this->db
->getType() == 'oracle' ) {
203 # Insert 0 user to prevent FK violations
205 $this->db
->insert( 'user', array(
207 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
209 # Insert 0 page to prevent FK violations
211 $this->db
->insert( 'page', array(
213 'page_namespace' => 0,
215 'page_restrictions' => NULL,
217 'page_is_redirect' => 0,
220 'page_touched' => $this->db
->timestamp(),
222 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
226 User
::resetIdByNameCache();
229 $user = User
::newFromName( 'UTSysop' );
231 if ( $user->idForName() == 0 ) {
232 $user->addToDatabase();
233 $user->setPassword( 'UTSysopPassword' );
235 $user->addGroup( 'sysop' );
236 $user->addGroup( 'bureaucrat' );
237 $user->saveSettings();
241 //Make 1 page with 1 revision
242 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
243 if ( !$page->getId() == 0 ) {
244 $page->doEditContent(
245 new WikitextContent( 'UTContent' ),
249 User
::newFromName( 'UTSysop' ) );
253 private function initDB() {
255 if ( $wgDBprefix === $this->dbPrefix() ) {
256 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
259 $tablesCloned = $this->listTables();
260 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
261 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
263 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
264 CloneDatabase
::changePrefix( $this->dbPrefix() );
268 $dbClone->cloneTableStructure();
271 if ( $this->db
->getType() == 'oracle' ) {
272 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
277 * Empty all tables so they can be repopulated for tests
279 private function resetDB() {
281 if ( $this->db
->getType() == 'oracle' ) {
282 if ( $this->useTemporaryTables
) {
283 wfGetLB()->closeAll();
284 $this->db
= wfGetDB( DB_MASTER
);
286 foreach( $this->tablesUsed
as $tbl ) {
287 if( $tbl == 'interwiki') continue;
288 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
292 foreach( $this->tablesUsed
as $tbl ) {
293 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
294 $this->db
->delete( $tbl, '*', __METHOD__
);
300 function __call( $func, $args ) {
301 static $compatibility = array(
302 'assertInternalType' => 'assertType',
303 'assertNotInternalType' => 'assertNotType',
304 'assertInstanceOf' => 'assertType',
305 'assertEmpty' => 'assertEmpty2',
308 if ( method_exists( $this->suite
, $func ) ) {
309 return call_user_func_array( array( $this->suite
, $func ), $args);
310 } elseif ( isset( $compatibility[$func] ) ) {
311 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
313 throw new MWException( "Called non-existant $func method on "
314 . get_class( $this ) );
318 private function assertEmpty2( $value, $msg ) {
319 return $this->assertTrue( $value == '', $msg );
322 static private function unprefixTable( $tableName ) {
324 return substr( $tableName, strlen( $wgDBprefix ) );
327 static private function isNotUnittest( $table ) {
328 return strpos( $table, 'unittest_' ) !== 0;
331 protected function listTables() {
334 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
335 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
337 // Don't duplicate test tables from the previous fataled run
338 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
340 if ( $this->db
->getType() == 'sqlite' ) {
341 $tables = array_flip( $tables );
342 // these are subtables of searchindex and don't need to be duped/dropped separately
343 unset( $tables['searchindex_content'] );
344 unset( $tables['searchindex_segdir'] );
345 unset( $tables['searchindex_segments'] );
346 $tables = array_flip( $tables );
351 protected function checkDbIsSupported() {
352 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
353 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
357 public function getCliArg( $offset ) {
359 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
360 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
365 public function setCliArg( $offset, $value ) {
367 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
372 * Don't throw a warning if $function is deprecated and called later
374 * @param $function String
377 function hideDeprecated( $function ) {
378 wfSuppressWarnings();
379 wfDeprecated( $function );
384 * Asserts that the given database query yields the rows given by $expectedRows.
385 * The expected rows should be given as indexed (not associative) arrays, with
386 * the values given in the order of the columns in the $fields parameter.
387 * Note that the rows are sorted by the columns given in $fields.
391 * @param $table String|Array the table(s) to query
392 * @param $fields String|Array the columns to include in the result (and to sort by)
393 * @param $condition String|Array "where" condition(s)
394 * @param $expectedRows Array - an array of arrays giving the expected rows.
396 * @throws MWException if this test cases's needsDB() method doesn't return true.
397 * Test cases can use "@group Database" to enable database test support,
398 * or list the tables under testing in $this->tablesUsed, or override the
401 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
402 if ( !$this->needsDB() ) {
403 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
404 ' method should return true. Use @group Database or $this->tablesUsed.');
407 $db = wfGetDB( DB_SLAVE
);
409 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
410 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
414 foreach ( $expectedRows as $expected ) {
415 $r = $res->fetchRow();
416 self
::stripStringKeys( $r );
419 $this->assertNotEmpty( $r, "row #$i missing" );
421 $this->assertEquals( $expected, $r, "row #$i mismatches" );
424 $r = $res->fetchRow();
425 self
::stripStringKeys( $r );
427 $this->assertFalse( $r, "found extra row (after #$i)" );
431 * Utility method taking an array of elements and wrapping
432 * each element in it's own array. Useful for data providers
433 * that only return a single argument.
437 * @param array $elements
441 protected function arrayWrap( array $elements ) {
443 function( $element ) {
444 return array( $element );
451 * Assert that two arrays are equal. By default this means that both arrays need to hold
452 * the same set of values. Using additional arguments, order and associated key can also
453 * be set as relevant.
457 * @param array $expected
458 * @param array $actual
459 * @param boolean $ordered If the order of the values should match
460 * @param boolean $named If the keys should match
462 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
464 $this->objectAssociativeSort( $expected );
465 $this->objectAssociativeSort( $actual );
469 $expected = array_values( $expected );
470 $actual = array_values( $actual );
473 call_user_func_array(
474 array( $this, 'assertEquals' ),
475 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
480 * Put each HTML element on its own line and then equals() the results
482 * Use for nicely formatting of PHPUnit diff output when comparing very
487 * @param String $expected HTML on oneline
488 * @param String $actual HTML on oneline
489 * @param String $msg Optional message
491 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
492 $expected = str_replace( '>', ">\n", $expected );
493 $actual = str_replace( '>', ">\n", $actual );
495 $this->assertEquals( $expected, $actual, $msg );
499 * Does an associative sort that works for objects.
503 * @param array $array
505 protected function objectAssociativeSort( array &$array ) {
509 return serialize( $a ) > serialize( $b ) ?
1 : -1;
515 * Utility function for eliminating all string keys from an array.
516 * Useful to turn a database result row as returned by fetchRow() into
517 * a pure indexed array.
521 * @param $r mixed the array to remove string keys from.
523 protected static function stripStringKeys( &$r ) {
524 if ( !is_array( $r ) ) {
528 foreach ( $r as $k => $v ) {
529 if ( is_string( $k ) ) {
536 * Asserts that the provided variable is of the specified
537 * internal type or equals the $value argument. This is useful
538 * for testing return types of functions that return a certain
539 * type or *value* when not set or on error.
543 * @param string $type
544 * @param mixed $actual
545 * @param mixed $value
546 * @param string $message
548 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
549 if ( $actual === $value ) {
550 $this->assertTrue( true, $message );
553 $this->assertType( $type, $actual, $message );
558 * Asserts the type of the provided value. This can be either
559 * in internal type such as boolean or integer, or a class or
560 * interface the value extends or implements.
564 * @param string $type
565 * @param mixed $actual
566 * @param string $message
568 protected function assertType( $type, $actual, $message = '' ) {
569 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
570 $this->assertInstanceOf( $type, $actual, $message );
573 $this->assertInternalType( $type, $actual, $message );