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();
33 * Holds original values of MediaWiki configuration settings
34 * to be restored in tearDown().
35 * See also setMwGlobal().
38 private $mwGlobals = array();
41 * Table name prefixes. Oracle likes it shorter.
43 const DB_PREFIX
= 'unittest_';
44 const ORA_DB_PREFIX
= 'ut_';
46 protected $supportedDBs = array(
53 function __construct( $name = null, array $data = array(), $dataName = '' ) {
54 parent
::__construct( $name, $data, $dataName );
56 $this->backupGlobals
= false;
57 $this->backupStaticAttributes
= false;
60 function run( PHPUnit_Framework_TestResult
$result = NULL ) {
61 /* Some functions require some kind of caching, and will end up using the db,
62 * which we can't allow, as that would open a new connection for mysql.
63 * Replace with a HashBag. They would not be going to persist anyway.
65 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
67 if( $this->needsDB() ) {
70 $this->useTemporaryTables
= !$this->getCliArg( 'use-normal-tables' );
71 $this->reuseDB
= $this->getCliArg('reuse-db');
73 $this->db
= wfGetDB( DB_MASTER
);
75 $this->checkDbIsSupported();
77 $this->oldTablePrefix
= $wgDBprefix;
79 if( !self
::$dbSetup ) {
81 self
::$dbSetup = true;
84 $this->addCoreDBData();
87 parent
::run( $result );
91 parent
::run( $result );
96 * obtains a new temporary file name
98 * The obtained filename is enlisted to be removed upon tearDown
100 * @returns string: absolute name of the temporary file
102 protected function getNewTempFile() {
103 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
104 $this->tmpfiles
[] = $fname;
109 * obtains a new temporary directory
111 * The obtained directory is enlisted to be removed (recursively with all its contained
112 * files) upon tearDown.
114 * @returns string: absolute name of the temporary directory
116 protected function getNewTempDirectory() {
117 // Starting of with a temporary /file/.
118 $fname = $this->getNewTempFile();
120 // Converting the temporary /file/ to a /directory/
122 // The following is not atomic, but at least we now have a single place,
123 // where temporary directory creation is bundled and can be improved
125 $this->assertTrue( wfMkdirParents( $fname ) );
130 * setUp and tearDown should (where significant)
131 * happen in reverse order.
133 protected function setUp() {
137 //@todo: global variables to restore for *every* test
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();
164 protected function tearDown() {
165 // Cleaning up temporary files
166 foreach ( $this->tmpfiles
as $fname ) {
167 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
169 } elseif ( is_dir( $fname ) ) {
170 wfRecursiveRemoveDir( $fname );
174 // Clean up open transactions
175 if ( $this->needsDB() && $this->db
) {
176 while( $this->db
->trxLevel() > 0 ) {
177 $this->db
->rollback();
181 // Restore mw globals
182 foreach ( $this->mwGlobals
as $key => $value ) {
183 $GLOBALS[$key] = $value;
185 $this->mwGlobals
= array();
191 * Individual test functions may override globals (either directly or through this
192 * setMwGlobals() function), however one must call this method at least once for
193 * each key within the setUp().
194 * That way the key is added to the array of globals that will be reset afterwards
195 * in the tearDown(). And, equally important, that way all other tests are executed
196 * with the same settings (instead of using the unreliable local settings for most
197 * tests and fix it only for some tests).
201 * protected function setUp() {
202 * $this->setMwGlobals( 'wgRestrictStuff', true );
205 * function testFoo() {}
207 * function testBar() {}
208 * $this->assertTrue( self::getX()->doStuff() );
210 * $this->setMwGlobals( 'wgRestrictStuff', false );
211 * $this->assertTrue( self::getX()->doStuff() );
214 * function testQuux() {}
217 * @param array|string $pairs Key to the global variable, or an array
218 * of key/value pairs.
219 * @param mixed $value Value to set the global to (ignored
220 * if an array is given as first argument).
222 protected function setMwGlobals( $pairs, $value = null ) {
224 // Normalize (string, value) to an array
225 if( is_string( $pairs ) ) {
226 $pairs = array( $pairs => $value );
229 foreach ( $pairs as $key => $value ) {
230 // NOTE: make sure we only save the global once or a second call to
231 // setMwGlobals() on the same global would override the original
233 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
234 $this->mwGlobals
[$key] = $GLOBALS[$key];
237 // Override the global
238 $GLOBALS[$key] = $value;
243 * Merges the given values into a MW global array variable.
244 * Useful for setting some entries in a configuration array, instead of
245 * setting the entire array.
247 * @param String $name The name of the global, as in wgFooBar
248 * @param Array $values The array containing the entries to set in that global
250 * @throws MWException if the designated global is not an array.
252 protected function mergeMwGlobalArrayValue( $name, $values ) {
253 if ( !isset( $GLOBALS[$name] ) ) {
256 if ( !is_array( $GLOBALS[$name] ) ) {
257 throw new MWException( "MW global $name is not an array." );
260 // NOTE: do not use array_merge, it screws up for numeric keys.
261 $merged = $GLOBALS[$name];
262 foreach ( $values as $k => $v ) {
267 $this->setMwGlobals( $name, $merged );
270 function dbPrefix() {
271 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
275 # if the test says it uses database tables, it needs the database
276 if ( $this->tablesUsed
) {
280 # if the test says it belongs to the Database group, it needs the database
281 $rc = new ReflectionClass( $this );
282 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
290 * Stub. If a test needs to add additional data to the database, it should
291 * implement this method and do so
293 function addDBData() {}
295 private function addCoreDBData() {
296 # disabled for performance
297 #$this->tablesUsed[] = 'page';
298 #$this->tablesUsed[] = 'revision';
300 if ( $this->db
->getType() == 'oracle' ) {
302 # Insert 0 user to prevent FK violations
304 $this->db
->insert( 'user', array(
306 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
308 # Insert 0 page to prevent FK violations
310 $this->db
->insert( 'page', array(
312 'page_namespace' => 0,
314 'page_restrictions' => NULL,
316 'page_is_redirect' => 0,
319 'page_touched' => $this->db
->timestamp(),
321 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
325 User
::resetIdByNameCache();
328 $user = User
::newFromName( 'UTSysop' );
330 if ( $user->idForName() == 0 ) {
331 $user->addToDatabase();
332 $user->setPassword( 'UTSysopPassword' );
334 $user->addGroup( 'sysop' );
335 $user->addGroup( 'bureaucrat' );
336 $user->saveSettings();
340 //Make 1 page with 1 revision
341 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
342 if ( !$page->getId() == 0 ) {
343 $page->doEditContent(
344 new WikitextContent( 'UTContent' ),
348 User
::newFromName( 'UTSysop' ) );
352 private function initDB() {
354 if ( $wgDBprefix === $this->dbPrefix() ) {
355 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
358 $tablesCloned = $this->listTables();
359 $dbClone = new CloneDatabase( $this->db
, $tablesCloned, $this->dbPrefix() );
360 $dbClone->useTemporaryTables( $this->useTemporaryTables
);
362 if ( ( $this->db
->getType() == 'oracle' ||
!$this->useTemporaryTables
) && $this->reuseDB
) {
363 CloneDatabase
::changePrefix( $this->dbPrefix() );
367 $dbClone->cloneTableStructure();
370 if ( $this->db
->getType() == 'oracle' ) {
371 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
376 * Empty all tables so they can be repopulated for tests
378 private function resetDB() {
380 if ( $this->db
->getType() == 'oracle' ) {
381 if ( $this->useTemporaryTables
) {
382 wfGetLB()->closeAll();
383 $this->db
= wfGetDB( DB_MASTER
);
385 foreach( $this->tablesUsed
as $tbl ) {
386 if( $tbl == 'interwiki') continue;
387 $this->db
->query( 'TRUNCATE TABLE '.$this->db
->tableName($tbl), __METHOD__
);
391 foreach( $this->tablesUsed
as $tbl ) {
392 if( $tbl == 'interwiki' ||
$tbl == 'user' ) continue;
393 $this->db
->delete( $tbl, '*', __METHOD__
);
399 function __call( $func, $args ) {
400 static $compatibility = array(
401 'assertInternalType' => 'assertType',
402 'assertNotInternalType' => 'assertNotType',
403 'assertInstanceOf' => 'assertType',
404 'assertEmpty' => 'assertEmpty2',
407 if ( method_exists( $this->suite
, $func ) ) {
408 return call_user_func_array( array( $this->suite
, $func ), $args);
409 } elseif ( isset( $compatibility[$func] ) ) {
410 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
412 throw new MWException( "Called non-existant $func method on "
413 . get_class( $this ) );
417 private function assertEmpty2( $value, $msg ) {
418 return $this->assertTrue( $value == '', $msg );
421 static private function unprefixTable( $tableName ) {
423 return substr( $tableName, strlen( $wgDBprefix ) );
426 static private function isNotUnittest( $table ) {
427 return strpos( $table, 'unittest_' ) !== 0;
430 protected function listTables() {
433 $tables = $this->db
->listTables( $wgDBprefix, __METHOD__
);
434 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
436 // Don't duplicate test tables from the previous fataled run
437 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
439 if ( $this->db
->getType() == 'sqlite' ) {
440 $tables = array_flip( $tables );
441 // these are subtables of searchindex and don't need to be duped/dropped separately
442 unset( $tables['searchindex_content'] );
443 unset( $tables['searchindex_segdir'] );
444 unset( $tables['searchindex_segments'] );
445 $tables = array_flip( $tables );
450 protected function checkDbIsSupported() {
451 if( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
452 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
456 public function getCliArg( $offset ) {
458 if( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
459 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
464 public function setCliArg( $offset, $value ) {
466 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
471 * Don't throw a warning if $function is deprecated and called later
473 * @param $function String
476 function hideDeprecated( $function ) {
477 wfSuppressWarnings();
478 wfDeprecated( $function );
483 * Asserts that the given database query yields the rows given by $expectedRows.
484 * The expected rows should be given as indexed (not associative) arrays, with
485 * the values given in the order of the columns in the $fields parameter.
486 * Note that the rows are sorted by the columns given in $fields.
490 * @param $table String|Array the table(s) to query
491 * @param $fields String|Array the columns to include in the result (and to sort by)
492 * @param $condition String|Array "where" condition(s)
493 * @param $expectedRows Array - an array of arrays giving the expected rows.
495 * @throws MWException if this test cases's needsDB() method doesn't return true.
496 * Test cases can use "@group Database" to enable database test support,
497 * or list the tables under testing in $this->tablesUsed, or override the
500 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
501 if ( !$this->needsDB() ) {
502 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
503 ' method should return true. Use @group Database or $this->tablesUsed.');
506 $db = wfGetDB( DB_SLAVE
);
508 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
509 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
513 foreach ( $expectedRows as $expected ) {
514 $r = $res->fetchRow();
515 self
::stripStringKeys( $r );
518 $this->assertNotEmpty( $r, "row #$i missing" );
520 $this->assertEquals( $expected, $r, "row #$i mismatches" );
523 $r = $res->fetchRow();
524 self
::stripStringKeys( $r );
526 $this->assertFalse( $r, "found extra row (after #$i)" );
530 * Utility method taking an array of elements and wrapping
531 * each element in it's own array. Useful for data providers
532 * that only return a single argument.
536 * @param array $elements
540 protected function arrayWrap( array $elements ) {
542 function( $element ) {
543 return array( $element );
550 * Assert that two arrays are equal. By default this means that both arrays need to hold
551 * the same set of values. Using additional arguments, order and associated key can also
552 * be set as relevant.
556 * @param array $expected
557 * @param array $actual
558 * @param boolean $ordered If the order of the values should match
559 * @param boolean $named If the keys should match
561 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
563 $this->objectAssociativeSort( $expected );
564 $this->objectAssociativeSort( $actual );
568 $expected = array_values( $expected );
569 $actual = array_values( $actual );
572 call_user_func_array(
573 array( $this, 'assertEquals' ),
574 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
579 * Put each HTML element on its own line and then equals() the results
581 * Use for nicely formatting of PHPUnit diff output when comparing very
586 * @param String $expected HTML on oneline
587 * @param String $actual HTML on oneline
588 * @param String $msg Optional message
590 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
591 $expected = str_replace( '>', ">\n", $expected );
592 $actual = str_replace( '>', ">\n", $actual );
594 $this->assertEquals( $expected, $actual, $msg );
598 * Does an associative sort that works for objects.
602 * @param array $array
604 protected function objectAssociativeSort( array &$array ) {
608 return serialize( $a ) > serialize( $b ) ?
1 : -1;
614 * Utility function for eliminating all string keys from an array.
615 * Useful to turn a database result row as returned by fetchRow() into
616 * a pure indexed array.
620 * @param $r mixed the array to remove string keys from.
622 protected static function stripStringKeys( &$r ) {
623 if ( !is_array( $r ) ) {
627 foreach ( $r as $k => $v ) {
628 if ( is_string( $k ) ) {
635 * Asserts that the provided variable is of the specified
636 * internal type or equals the $value argument. This is useful
637 * for testing return types of functions that return a certain
638 * type or *value* when not set or on error.
642 * @param string $type
643 * @param mixed $actual
644 * @param mixed $value
645 * @param string $message
647 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
648 if ( $actual === $value ) {
649 $this->assertTrue( true, $message );
652 $this->assertType( $type, $actual, $message );
657 * Asserts the type of the provided value. This can be either
658 * in internal type such as boolean or integer, or a class or
659 * interface the value extends or implements.
663 * @param string $type
664 * @param mixed $actual
665 * @param string $message
667 protected function assertType( $type, $actual, $message = '' ) {
668 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
669 $this->assertInstanceOf( $type, $actual, $message );
672 $this->assertInternalType( $type, $actual, $message );
677 * Returns true iff the given namespace defaults to Wikitext
678 * according to $wgNamespaceContentModels
680 * @param int $ns The namespace ID to check
685 protected function isWikitextNS( $ns ) {
686 global $wgNamespaceContentModels;
688 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
689 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
696 * Returns the ID of a namespace that defaults to Wikitext.
697 * Throws an MWException if there is none.
699 * @return int the ID of the wikitext Namespace
702 protected function getDefaultWikitextNS() {
703 global $wgNamespaceContentModels;
705 static $wikitextNS = null; // this is not going to change
706 if ( $wikitextNS !== null ) {
710 // quickly short out on most common case:
711 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
715 // NOTE: prefer content namespaces
716 $namespaces = array_unique( array_merge(
717 MWNamespace
::getContentNamespaces(),
718 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
719 MWNamespace
::getValidNamespaces()
722 $namespaces = array_diff( $namespaces, array(
723 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
726 $talk = array_filter( $namespaces, function ( $ns ) {
727 return MWNamespace
::isTalk( $ns );
730 // prefer non-talk pages
731 $namespaces = array_diff( $namespaces, $talk );
732 $namespaces = array_merge( $namespaces, $talk );
734 // check default content model of each namespace
735 foreach ( $namespaces as $ns ) {
736 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
737 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
) {
745 // @todo: Inside a test, we could skip the test as incomplete.
746 // But frequently, this is used in fixture setup.
747 throw new MWException( "No namespace defaults to wikitext!" );