More complete, more straightforward JobQueueMemoryTest
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob861e3bd86426dbc4d10e148bbb9c32ff69bf37bd
1 <?php
3 /**
4 * @since 1.18
5 */
6 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
7 /**
8 * $called tracks whether the setUp and tearDown method has been called.
9 * class extending MediaWikiTestCase usually override setUp and tearDown
10 * but forget to call the parent.
12 * The array format takes a method name as key and anything as a value.
13 * By asserting the key exist, we know the child class has called the
14 * parent.
16 * This property must be private, we do not want child to override it,
17 * they should call the appropriate parent method instead.
19 private $called = array();
21 /**
22 * @var TestUser[]
23 * @since 1.20
25 public static $users;
27 /**
28 * @var DatabaseBase
29 * @since 1.18
31 protected $db;
33 /**
34 * @var array
35 * @since 1.19
37 protected $tablesUsed = array(); // tables with data
39 private static $useTemporaryTables = true;
40 private static $reuseDB = false;
41 private static $dbSetup = false;
42 private static $oldTablePrefix = false;
44 /**
45 * Original value of PHP's error_reporting setting.
47 * @var int
49 private $phpErrorLevel;
51 /**
52 * Holds the paths of temporary files/directories created through getNewTempFile,
53 * and getNewTempDirectory
55 * @var array
57 private $tmpFiles = array();
59 /**
60 * Holds original values of MediaWiki configuration settings
61 * to be restored in tearDown().
62 * See also setMwGlobals().
63 * @var array
65 private $mwGlobals = array();
67 /**
68 * Table name prefixes. Oracle likes it shorter.
70 const DB_PREFIX = 'unittest_';
71 const ORA_DB_PREFIX = 'ut_';
73 /**
74 * @var array
75 * @since 1.18
77 protected $supportedDBs = array(
78 'mysql',
79 'sqlite',
80 'postgres',
81 'oracle'
84 public function __construct( $name = null, array $data = array(), $dataName = '' ) {
85 parent::__construct( $name, $data, $dataName );
87 $this->backupGlobals = false;
88 $this->backupStaticAttributes = false;
91 public function __destruct() {
92 // Complain if self::setUp() was called, but not self::tearDown()
93 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
94 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
95 throw new MWException( get_called_class() . "::tearDown() must call parent::tearDown()" );
99 public function run( PHPUnit_Framework_TestResult $result = null ) {
100 /* Some functions require some kind of caching, and will end up using the db,
101 * which we can't allow, as that would open a new connection for mysql.
102 * Replace with a HashBag. They would not be going to persist anyway.
104 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
106 // Sandbox APC by replacing with in-process hash instead.
107 // Ensures values are removed between tests.
108 ObjectCache::$instances['apc'] =
109 ObjectCache::$instances['xcache'] =
110 ObjectCache::$instances['wincache'] = new HashBagOStuff;
112 $needsResetDB = false;
114 if ( $this->needsDB() ) {
115 // set up a DB connection for this test to use
117 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
118 self::$reuseDB = $this->getCliArg( 'reuse-db' );
120 $this->db = wfGetDB( DB_MASTER );
122 $this->checkDbIsSupported();
124 if ( !self::$dbSetup ) {
125 // switch to a temporary clone of the database
126 self::setupTestDB( $this->db, $this->dbPrefix() );
128 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
129 $this->resetDB();
132 $this->addCoreDBData();
133 $this->addDBData();
134 $needsResetDB = true;
137 parent::run( $result );
139 if ( $needsResetDB ) {
140 $this->resetDB();
145 * @since 1.21
147 * @return bool
149 public function usesTemporaryTables() {
150 return self::$useTemporaryTables;
154 * Obtains a new temporary file name
156 * The obtained filename is enlisted to be removed upon tearDown
158 * @since 1.20
160 * @return string Absolute name of the temporary file
162 protected function getNewTempFile() {
163 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
164 $this->tmpFiles[] = $fileName;
166 return $fileName;
170 * obtains a new temporary directory
172 * The obtained directory is enlisted to be removed (recursively with all its contained
173 * files) upon tearDown.
175 * @since 1.20
177 * @return string Absolute name of the temporary directory
179 protected function getNewTempDirectory() {
180 // Starting of with a temporary /file/.
181 $fileName = $this->getNewTempFile();
183 // Converting the temporary /file/ to a /directory/
184 // The following is not atomic, but at least we now have a single place,
185 // where temporary directory creation is bundled and can be improved
186 unlink( $fileName );
187 $this->assertTrue( wfMkdirParents( $fileName ) );
189 return $fileName;
192 protected function setUp() {
193 parent::setUp();
194 $this->called['setUp'] = true;
196 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
198 // Cleaning up temporary files
199 foreach ( $this->tmpFiles as $fileName ) {
200 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
201 unlink( $fileName );
202 } elseif ( is_dir( $fileName ) ) {
203 wfRecursiveRemoveDir( $fileName );
207 if ( $this->needsDB() && $this->db ) {
208 // Clean up open transactions
209 while ( $this->db->trxLevel() > 0 ) {
210 $this->db->rollback( __METHOD__, 'flush' );
214 DeferredUpdates::clearPendingUpdates();
216 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
219 protected function addTmpFiles( $files ) {
220 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
223 protected function tearDown() {
224 global $wgRequest;
226 $status = ob_get_status();
227 if ( isset( $status['name'] ) &&
228 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
230 ob_end_flush();
233 $this->called['tearDown'] = true;
234 // Cleaning up temporary files
235 foreach ( $this->tmpFiles as $fileName ) {
236 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
237 unlink( $fileName );
238 } elseif ( is_dir( $fileName ) ) {
239 wfRecursiveRemoveDir( $fileName );
243 if ( $this->needsDB() && $this->db ) {
244 // Clean up open transactions
245 while ( $this->db->trxLevel() > 0 ) {
246 $this->db->rollback( __METHOD__, 'flush' );
250 // Restore mw globals
251 foreach ( $this->mwGlobals as $key => $value ) {
252 $GLOBALS[$key] = $value;
254 $this->mwGlobals = array();
255 RequestContext::resetMain();
256 MediaHandler::resetCache();
257 if ( session_id() !== '' ) {
258 session_write_close();
259 session_id( '' );
261 $wgRequest = new FauxRequest();
262 MediaWiki\Session\SessionManager::resetCache();
264 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
266 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
267 ini_set( 'error_reporting', $this->phpErrorLevel );
269 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
270 $newHex = strtoupper( dechex( $phpErrorLevel ) );
271 $message = "PHP error_reporting setting was left dirty: "
272 . "was 0x$oldHex before test, 0x$newHex after test!";
274 $this->fail( $message );
277 parent::tearDown();
281 * Make sure MediaWikiTestCase extending classes have called their
282 * parent setUp method
284 final public function testMediaWikiTestCaseParentSetupCalled() {
285 $this->assertArrayHasKey( 'setUp', $this->called,
286 get_called_class() . "::setUp() must call parent::setUp()"
291 * Sets a global, maintaining a stashed version of the previous global to be
292 * restored in tearDown
294 * The key is added to the array of globals that will be reset afterwards
295 * in the tearDown().
297 * @example
298 * <code>
299 * protected function setUp() {
300 * $this->setMwGlobals( 'wgRestrictStuff', true );
303 * function testFoo() {}
305 * function testBar() {}
306 * $this->assertTrue( self::getX()->doStuff() );
308 * $this->setMwGlobals( 'wgRestrictStuff', false );
309 * $this->assertTrue( self::getX()->doStuff() );
312 * function testQuux() {}
313 * </code>
315 * @param array|string $pairs Key to the global variable, or an array
316 * of key/value pairs.
317 * @param mixed $value Value to set the global to (ignored
318 * if an array is given as first argument).
320 * @since 1.21
322 protected function setMwGlobals( $pairs, $value = null ) {
323 if ( is_string( $pairs ) ) {
324 $pairs = array( $pairs => $value );
327 $this->stashMwGlobals( array_keys( $pairs ) );
329 foreach ( $pairs as $key => $value ) {
330 $GLOBALS[$key] = $value;
335 * Stashes the global, will be restored in tearDown()
337 * Individual test functions may override globals through the setMwGlobals() function
338 * or directly. When directly overriding globals their keys should first be passed to this
339 * method in setUp to avoid breaking global state for other tests
341 * That way all other tests are executed with the same settings (instead of using the
342 * unreliable local settings for most tests and fix it only for some tests).
344 * @param array|string $globalKeys Key to the global variable, or an array of keys.
346 * @throws Exception When trying to stash an unset global
347 * @since 1.23
349 protected function stashMwGlobals( $globalKeys ) {
350 if ( is_string( $globalKeys ) ) {
351 $globalKeys = array( $globalKeys );
354 foreach ( $globalKeys as $globalKey ) {
355 // NOTE: make sure we only save the global once or a second call to
356 // setMwGlobals() on the same global would override the original
357 // value.
358 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
359 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
360 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
362 // NOTE: we serialize then unserialize the value in case it is an object
363 // this stops any objects being passed by reference. We could use clone
364 // and if is_object but this does account for objects within objects!
365 try {
366 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
368 // NOTE; some things such as Closures are not serializable
369 // in this case just set the value!
370 catch ( Exception $e ) {
371 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
378 * Merges the given values into a MW global array variable.
379 * Useful for setting some entries in a configuration array, instead of
380 * setting the entire array.
382 * @param string $name The name of the global, as in wgFooBar
383 * @param array $values The array containing the entries to set in that global
385 * @throws MWException If the designated global is not an array.
387 * @since 1.21
389 protected function mergeMwGlobalArrayValue( $name, $values ) {
390 if ( !isset( $GLOBALS[$name] ) ) {
391 $merged = $values;
392 } else {
393 if ( !is_array( $GLOBALS[$name] ) ) {
394 throw new MWException( "MW global $name is not an array." );
397 // NOTE: do not use array_merge, it screws up for numeric keys.
398 $merged = $GLOBALS[$name];
399 foreach ( $values as $k => $v ) {
400 $merged[$k] = $v;
404 $this->setMwGlobals( $name, $merged );
408 * @return string
409 * @since 1.18
411 public function dbPrefix() {
412 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
416 * @return bool
417 * @since 1.18
419 public function needsDB() {
420 # if the test says it uses database tables, it needs the database
421 if ( $this->tablesUsed ) {
422 return true;
425 # if the test says it belongs to the Database group, it needs the database
426 $rc = new ReflectionClass( $this );
427 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
428 return true;
431 return false;
435 * Insert a new page.
437 * Should be called from addDBData().
439 * @since 1.25
440 * @param string $pageName Page name
441 * @param string $text Page's content
442 * @return array Title object and page id
444 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
445 $title = Title::newFromText( $pageName, 0 );
447 $user = User::newFromName( 'UTSysop' );
448 $comment = __METHOD__ . ': Sample page for unit test.';
450 // Avoid memory leak...?
451 // LinkCache::singleton()->clear();
452 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
454 $page = WikiPage::factory( $title );
455 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
457 return array(
458 'title' => $title,
459 'id' => $page->getId(),
464 * Stub. If a test needs to add additional data to the database, it should
465 * implement this method and do so
467 * @since 1.18
469 public function addDBData() {
472 private function addCoreDBData() {
473 if ( $this->db->getType() == 'oracle' ) {
475 # Insert 0 user to prevent FK violations
476 # Anonymous user
477 $this->db->insert( 'user', array(
478 'user_id' => 0,
479 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
481 # Insert 0 page to prevent FK violations
482 # Blank page
483 $this->db->insert( 'page', array(
484 'page_id' => 0,
485 'page_namespace' => 0,
486 'page_title' => ' ',
487 'page_restrictions' => null,
488 'page_is_redirect' => 0,
489 'page_is_new' => 0,
490 'page_random' => 0,
491 'page_touched' => $this->db->timestamp(),
492 'page_latest' => 0,
493 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
496 User::resetIdByNameCache();
498 // Make sysop user
499 $user = User::newFromName( 'UTSysop' );
501 if ( $user->idForName() == 0 ) {
502 $user->addToDatabase();
503 TestUser::setPasswordForUser( $user, 'UTSysopPassword' );
506 // Always set groups, because $this->resetDB() wipes them out
507 $user->addGroup( 'sysop' );
508 $user->addGroup( 'bureaucrat' );
510 // Make 1 page with 1 revision
511 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
512 if ( $page->getId() == 0 ) {
513 $page->doEditContent(
514 new WikitextContent( 'UTContent' ),
515 'UTPageSummary',
516 EDIT_NEW,
517 false,
518 $user
521 // doEditContent() probably started the session via
522 // User::loadFromSession(). Close it now.
523 if ( session_id() !== '' ) {
524 session_write_close();
525 session_id( '' );
531 * Restores MediaWiki to using the table set (table prefix) it was using before
532 * setupTestDB() was called. Useful if we need to perform database operations
533 * after the test run has finished (such as saving logs or profiling info).
535 * @since 1.21
537 public static function teardownTestDB() {
538 global $wgJobClasses;
540 if ( !self::$dbSetup ) {
541 return;
544 foreach ( $wgJobClasses as $type => $class ) {
545 // Delete any jobs under the clone DB (or old prefix in other stores)
546 JobQueueGroup::singleton()->get( $type )->delete();
549 CloneDatabase::changePrefix( self::$oldTablePrefix );
551 self::$oldTablePrefix = false;
552 self::$dbSetup = false;
556 * Creates an empty skeleton of the wiki database by cloning its structure
557 * to equivalent tables using the given $prefix. Then sets MediaWiki to
558 * use the new set of tables (aka schema) instead of the original set.
560 * This is used to generate a dummy table set, typically consisting of temporary
561 * tables, that will be used by tests instead of the original wiki database tables.
563 * @since 1.21
565 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
566 * by teardownTestDB() to return the wiki to using the original table set.
568 * @note this method only works when first called. Subsequent calls have no effect,
569 * even if using different parameters.
571 * @param DatabaseBase $db The database connection
572 * @param string $prefix The prefix to use for the new table set (aka schema).
574 * @throws MWException If the database table prefix is already $prefix
576 public static function setupTestDB( DatabaseBase $db, $prefix ) {
577 global $wgDBprefix;
578 if ( $wgDBprefix === $prefix ) {
579 throw new MWException(
580 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
583 if ( self::$dbSetup ) {
584 return;
587 $tablesCloned = self::listTables( $db );
588 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
589 $dbClone->useTemporaryTables( self::$useTemporaryTables );
591 self::$dbSetup = true;
592 self::$oldTablePrefix = $wgDBprefix;
594 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
595 CloneDatabase::changePrefix( $prefix );
597 return;
598 } else {
599 $dbClone->cloneTableStructure();
602 if ( $db->getType() == 'oracle' ) {
603 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
608 * Empty all tables so they can be repopulated for tests
610 private function resetDB() {
611 if ( $this->db ) {
612 if ( $this->db->getType() == 'oracle' ) {
613 if ( self::$useTemporaryTables ) {
614 wfGetLB()->closeAll();
615 $this->db = wfGetDB( DB_MASTER );
616 } else {
617 foreach ( $this->tablesUsed as $tbl ) {
618 if ( $tbl == 'interwiki' ) {
619 continue;
621 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
624 } else {
625 foreach ( $this->tablesUsed as $tbl ) {
626 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
627 continue;
629 $this->db->delete( $tbl, '*', __METHOD__ );
636 * @since 1.18
638 * @param string $func
639 * @param array $args
641 * @return mixed
642 * @throws MWException
644 public function __call( $func, $args ) {
645 static $compatibility = array(
646 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
649 if ( isset( $compatibility[$func] ) ) {
650 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
651 } else {
652 throw new MWException( "Called non-existent $func method on "
653 . get_class( $this ) );
658 * Used as a compatibility method for phpunit < 3.7.32
659 * @param string $value
660 * @param string $msg
662 private function assertEmpty2( $value, $msg ) {
663 $this->assertTrue( $value == '', $msg );
666 private static function unprefixTable( $tableName ) {
667 global $wgDBprefix;
669 return substr( $tableName, strlen( $wgDBprefix ) );
672 private static function isNotUnittest( $table ) {
673 return strpos( $table, 'unittest_' ) !== 0;
677 * @since 1.18
679 * @param DatabaseBase $db
681 * @return array
683 public static function listTables( $db ) {
684 global $wgDBprefix;
686 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
688 if ( $db->getType() === 'mysql' ) {
689 # bug 43571: cannot clone VIEWs under MySQL
690 $views = $db->listViews( $wgDBprefix, __METHOD__ );
691 $tables = array_diff( $tables, $views );
693 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
695 // Don't duplicate test tables from the previous fataled run
696 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
698 if ( $db->getType() == 'sqlite' ) {
699 $tables = array_flip( $tables );
700 // these are subtables of searchindex and don't need to be duped/dropped separately
701 unset( $tables['searchindex_content'] );
702 unset( $tables['searchindex_segdir'] );
703 unset( $tables['searchindex_segments'] );
704 $tables = array_flip( $tables );
707 return $tables;
711 * @throws MWException
712 * @since 1.18
714 protected function checkDbIsSupported() {
715 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
716 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
721 * @since 1.18
722 * @param string $offset
723 * @return mixed
725 public function getCliArg( $offset ) {
726 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
727 return PHPUnitMaintClass::$additionalOptions[$offset];
732 * @since 1.18
733 * @param string $offset
734 * @param mixed $value
736 public function setCliArg( $offset, $value ) {
737 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
741 * Don't throw a warning if $function is deprecated and called later
743 * @since 1.19
745 * @param string $function
747 public function hideDeprecated( $function ) {
748 MediaWiki\suppressWarnings();
749 wfDeprecated( $function );
750 MediaWiki\restoreWarnings();
754 * Asserts that the given database query yields the rows given by $expectedRows.
755 * The expected rows should be given as indexed (not associative) arrays, with
756 * the values given in the order of the columns in the $fields parameter.
757 * Note that the rows are sorted by the columns given in $fields.
759 * @since 1.20
761 * @param string|array $table The table(s) to query
762 * @param string|array $fields The columns to include in the result (and to sort by)
763 * @param string|array $condition "where" condition(s)
764 * @param array $expectedRows An array of arrays giving the expected rows.
766 * @throws MWException If this test cases's needsDB() method doesn't return true.
767 * Test cases can use "@group Database" to enable database test support,
768 * or list the tables under testing in $this->tablesUsed, or override the
769 * needsDB() method.
771 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
772 if ( !$this->needsDB() ) {
773 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
774 ' method should return true. Use @group Database or $this->tablesUsed.' );
777 $db = wfGetDB( DB_SLAVE );
779 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
780 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
782 $i = 0;
784 foreach ( $expectedRows as $expected ) {
785 $r = $res->fetchRow();
786 self::stripStringKeys( $r );
788 $i += 1;
789 $this->assertNotEmpty( $r, "row #$i missing" );
791 $this->assertEquals( $expected, $r, "row #$i mismatches" );
794 $r = $res->fetchRow();
795 self::stripStringKeys( $r );
797 $this->assertFalse( $r, "found extra row (after #$i)" );
801 * Utility method taking an array of elements and wrapping
802 * each element in its own array. Useful for data providers
803 * that only return a single argument.
805 * @since 1.20
807 * @param array $elements
809 * @return array
811 protected function arrayWrap( array $elements ) {
812 return array_map(
813 function ( $element ) {
814 return array( $element );
816 $elements
821 * Assert that two arrays are equal. By default this means that both arrays need to hold
822 * the same set of values. Using additional arguments, order and associated key can also
823 * be set as relevant.
825 * @since 1.20
827 * @param array $expected
828 * @param array $actual
829 * @param bool $ordered If the order of the values should match
830 * @param bool $named If the keys should match
832 protected function assertArrayEquals( array $expected, array $actual,
833 $ordered = false, $named = false
835 if ( !$ordered ) {
836 $this->objectAssociativeSort( $expected );
837 $this->objectAssociativeSort( $actual );
840 if ( !$named ) {
841 $expected = array_values( $expected );
842 $actual = array_values( $actual );
845 call_user_func_array(
846 array( $this, 'assertEquals' ),
847 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
852 * Put each HTML element on its own line and then equals() the results
854 * Use for nicely formatting of PHPUnit diff output when comparing very
855 * simple HTML
857 * @since 1.20
859 * @param string $expected HTML on oneline
860 * @param string $actual HTML on oneline
861 * @param string $msg Optional message
863 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
864 $expected = str_replace( '>', ">\n", $expected );
865 $actual = str_replace( '>', ">\n", $actual );
867 $this->assertEquals( $expected, $actual, $msg );
871 * Does an associative sort that works for objects.
873 * @since 1.20
875 * @param array $array
877 protected function objectAssociativeSort( array &$array ) {
878 uasort(
879 $array,
880 function ( $a, $b ) {
881 return serialize( $a ) > serialize( $b ) ? 1 : -1;
887 * Utility function for eliminating all string keys from an array.
888 * Useful to turn a database result row as returned by fetchRow() into
889 * a pure indexed array.
891 * @since 1.20
893 * @param mixed $r The array to remove string keys from.
895 protected static function stripStringKeys( &$r ) {
896 if ( !is_array( $r ) ) {
897 return;
900 foreach ( $r as $k => $v ) {
901 if ( is_string( $k ) ) {
902 unset( $r[$k] );
908 * Asserts that the provided variable is of the specified
909 * internal type or equals the $value argument. This is useful
910 * for testing return types of functions that return a certain
911 * type or *value* when not set or on error.
913 * @since 1.20
915 * @param string $type
916 * @param mixed $actual
917 * @param mixed $value
918 * @param string $message
920 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
921 if ( $actual === $value ) {
922 $this->assertTrue( true, $message );
923 } else {
924 $this->assertType( $type, $actual, $message );
929 * Asserts the type of the provided value. This can be either
930 * in internal type such as boolean or integer, or a class or
931 * interface the value extends or implements.
933 * @since 1.20
935 * @param string $type
936 * @param mixed $actual
937 * @param string $message
939 protected function assertType( $type, $actual, $message = '' ) {
940 if ( class_exists( $type ) || interface_exists( $type ) ) {
941 $this->assertInstanceOf( $type, $actual, $message );
942 } else {
943 $this->assertInternalType( $type, $actual, $message );
948 * Returns true if the given namespace defaults to Wikitext
949 * according to $wgNamespaceContentModels
951 * @param int $ns The namespace ID to check
953 * @return bool
954 * @since 1.21
956 protected function isWikitextNS( $ns ) {
957 global $wgNamespaceContentModels;
959 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
960 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
963 return true;
967 * Returns the ID of a namespace that defaults to Wikitext.
969 * @throws MWException If there is none.
970 * @return int The ID of the wikitext Namespace
971 * @since 1.21
973 protected function getDefaultWikitextNS() {
974 global $wgNamespaceContentModels;
976 static $wikitextNS = null; // this is not going to change
977 if ( $wikitextNS !== null ) {
978 return $wikitextNS;
981 // quickly short out on most common case:
982 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
983 return NS_MAIN;
986 // NOTE: prefer content namespaces
987 $namespaces = array_unique( array_merge(
988 MWNamespace::getContentNamespaces(),
989 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
990 MWNamespace::getValidNamespaces()
991 ) );
993 $namespaces = array_diff( $namespaces, array(
994 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
995 ) );
997 $talk = array_filter( $namespaces, function ( $ns ) {
998 return MWNamespace::isTalk( $ns );
999 } );
1001 // prefer non-talk pages
1002 $namespaces = array_diff( $namespaces, $talk );
1003 $namespaces = array_merge( $namespaces, $talk );
1005 // check default content model of each namespace
1006 foreach ( $namespaces as $ns ) {
1007 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1008 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1011 $wikitextNS = $ns;
1013 return $wikitextNS;
1017 // give up
1018 // @todo Inside a test, we could skip the test as incomplete.
1019 // But frequently, this is used in fixture setup.
1020 throw new MWException( "No namespace defaults to wikitext!" );
1024 * Check, if $wgDiff3 is set and ready to merge
1025 * Will mark the calling test as skipped, if not ready
1027 * @since 1.21
1029 protected function checkHasDiff3() {
1030 global $wgDiff3;
1032 # This check may also protect against code injection in
1033 # case of broken installations.
1034 MediaWiki\suppressWarnings();
1035 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1036 MediaWiki\restoreWarnings();
1038 if ( !$haveDiff3 ) {
1039 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1044 * Check whether we have the 'gzip' commandline utility, will skip
1045 * the test whenever "gzip -V" fails.
1047 * Result is cached at the process level.
1049 * @return bool
1051 * @since 1.21
1053 protected function checkHasGzip() {
1054 static $haveGzip;
1056 if ( $haveGzip === null ) {
1057 $retval = null;
1058 wfShellExec( 'gzip -V', $retval );
1059 $haveGzip = ( $retval === 0 );
1062 if ( !$haveGzip ) {
1063 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1066 return $haveGzip;
1070 * Check if $extName is a loaded PHP extension, will skip the
1071 * test whenever it is not loaded.
1073 * @since 1.21
1074 * @param string $extName
1075 * @return bool
1077 protected function checkPHPExtension( $extName ) {
1078 $loaded = extension_loaded( $extName );
1079 if ( !$loaded ) {
1080 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1083 return $loaded;
1087 * Asserts that an exception of the specified type occurs when running
1088 * the provided code.
1090 * @since 1.21
1091 * @deprecated since 1.22 Use setExpectedException
1093 * @param callable $code
1094 * @param string $expected
1095 * @param string $message
1097 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1098 $pokemons = null;
1100 try {
1101 call_user_func( $code );
1102 } catch ( Exception $pokemons ) {
1103 // Gotta Catch 'Em All!
1106 if ( $message === '' ) {
1107 $message = 'An exception of type "' . $expected . '" should have been thrown';
1110 $this->assertInstanceOf( $expected, $pokemons, $message );
1114 * Asserts that the given string is a valid HTML snippet.
1115 * Wraps the given string in the required top level tags and
1116 * then calls assertValidHtmlDocument().
1117 * The snippet is expected to be HTML 5.
1119 * @since 1.23
1121 * @note Will mark the test as skipped if the "tidy" module is not installed.
1122 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1123 * when automatic tidying is disabled.
1125 * @param string $html An HTML snippet (treated as the contents of the body tag).
1127 protected function assertValidHtmlSnippet( $html ) {
1128 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1129 $this->assertValidHtmlDocument( $html );
1133 * Asserts that the given string is valid HTML document.
1135 * @since 1.23
1137 * @note Will mark the test as skipped if the "tidy" module is not installed.
1138 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1139 * when automatic tidying is disabled.
1141 * @param string $html A complete HTML document
1143 protected function assertValidHtmlDocument( $html ) {
1144 // Note: we only validate if the tidy PHP extension is available.
1145 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1146 // of tidy. In that case however, we can not reliably detect whether a failing validation
1147 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1148 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1149 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1150 $this->markTestSkipped( 'Tidy extension not installed' );
1153 $errorBuffer = '';
1154 MWTidy::checkErrors( $html, $errorBuffer );
1155 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1157 // Filter Tidy warnings which aren't useful for us.
1158 // Tidy eg. often cries about parameters missing which have actually
1159 // been deprecated since HTML4, thus we should not care about them.
1160 $errors = preg_grep(
1161 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1162 $allErrors, PREG_GREP_INVERT
1165 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1169 * @param array $matcher
1170 * @param string $actual
1171 * @param bool $isHtml
1173 * @return bool
1175 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1176 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1177 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1178 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1182 * Note: we are overriding this method to remove the deprecated error
1183 * @see https://phabricator.wikimedia.org/T71505
1184 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1185 * @deprecated
1187 * @param array $matcher
1188 * @param string $actual
1189 * @param string $message
1190 * @param bool $isHtml
1192 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1193 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1195 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1199 * @see MediaWikiTestCase::assertTag
1200 * @deprecated
1202 * @param array $matcher
1203 * @param string $actual
1204 * @param string $message
1205 * @param bool $isHtml
1207 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1208 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1210 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1214 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1215 * @return string
1217 public static function wfResetOutputBuffersBarrier( $buffer ) {
1218 return $buffer;