Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blobecc8ad1d47390f018a5378643066967c2ef507ce
1 <?php
3 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
4 public $suite;
5 public $regex = '';
6 public $runDisabled = false;
8 /**
9 * $called tracks whether the setUp and tearDown method has been called.
10 * class extending MediaWikiTestCase usually override setUp and tearDown
11 * but forget to call the parent.
13 * The array format takes a method name as key and anything as a value.
14 * By asserting the key exist, we know the child class has called the
15 * parent.
17 * This property must be private, we do not want child to override it,
18 * they should call the appropriate parent method instead.
20 private $called = array();
22 /**
23 * @var Array of TestUser
25 public static $users;
27 /**
28 * @var DatabaseBase
30 protected $db;
31 protected $tablesUsed = array(); // tables with data
33 private static $useTemporaryTables = true;
34 private static $reuseDB = false;
35 private static $dbSetup = false;
36 private static $oldTablePrefix = false;
38 /**
39 * Holds the paths of temporary files/directories created through getNewTempFile,
40 * and getNewTempDirectory
42 * @var array
44 private $tmpfiles = array();
46 /**
47 * Holds original values of MediaWiki configuration settings
48 * to be restored in tearDown().
49 * See also setMwGlobal().
50 * @var array
52 private $mwGlobals = array();
54 /**
55 * Table name prefixes. Oracle likes it shorter.
57 const DB_PREFIX = 'unittest_';
58 const ORA_DB_PREFIX = 'ut_';
60 protected $supportedDBs = array(
61 'mysql',
62 'sqlite',
63 'postgres',
64 'oracle'
67 function __construct( $name = null, array $data = array(), $dataName = '' ) {
68 parent::__construct( $name, $data, $dataName );
70 $this->backupGlobals = false;
71 $this->backupStaticAttributes = false;
74 function run( PHPUnit_Framework_TestResult $result = null ) {
75 /* Some functions require some kind of caching, and will end up using the db,
76 * which we can't allow, as that would open a new connection for mysql.
77 * Replace with a HashBag. They would not be going to persist anyway.
79 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
81 $needsResetDB = false;
82 $logName = get_class( $this ) . '::' . $this->getName( false );
84 if ( $this->needsDB() ) {
85 // set up a DB connection for this test to use
87 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
88 self::$reuseDB = $this->getCliArg( 'reuse-db' );
90 $this->db = wfGetDB( DB_MASTER );
92 $this->checkDbIsSupported();
94 if ( !self::$dbSetup ) {
95 wfProfileIn( $logName . ' (clone-db)' );
97 // switch to a temporary clone of the database
98 self::setupTestDB( $this->db, $this->dbPrefix() );
100 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
101 $this->resetDB();
104 wfProfileOut( $logName . ' (clone-db)' );
107 wfProfileIn( $logName . ' (prepare-db)' );
108 $this->addCoreDBData();
109 $this->addDBData();
110 wfProfileOut( $logName . ' (prepare-db)' );
112 $needsResetDB = true;
115 wfProfileIn( $logName );
116 parent::run( $result );
117 wfProfileOut( $logName );
119 if ( $needsResetDB ) {
120 wfProfileIn( $logName . ' (reset-db)' );
121 $this->resetDB();
122 wfProfileOut( $logName . ' (reset-db)' );
126 function usesTemporaryTables() {
127 return self::$useTemporaryTables;
131 * obtains a new temporary file name
133 * The obtained filename is enlisted to be removed upon tearDown
135 * @return string: absolute name of the temporary file
137 protected function getNewTempFile() {
138 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
139 $this->tmpfiles[] = $fname;
140 return $fname;
144 * obtains a new temporary directory
146 * The obtained directory is enlisted to be removed (recursively with all its contained
147 * files) upon tearDown.
149 * @return string: absolute name of the temporary directory
151 protected function getNewTempDirectory() {
152 // Starting of with a temporary /file/.
153 $fname = $this->getNewTempFile();
155 // Converting the temporary /file/ to a /directory/
157 // The following is not atomic, but at least we now have a single place,
158 // where temporary directory creation is bundled and can be improved
159 unlink( $fname );
160 $this->assertTrue( wfMkdirParents( $fname ) );
161 return $fname;
165 * setUp and tearDown should (where significant)
166 * happen in reverse order.
168 protected function setUp() {
169 wfProfileIn( __METHOD__ );
170 parent::setUp();
171 $this->called['setUp'] = 1;
174 //@todo: global variables to restore for *every* test
175 array(
176 'wgLang',
177 'wgContLang',
178 'wgLanguageCode',
179 'wgUser',
180 'wgTitle',
184 // Cleaning up temporary files
185 foreach ( $this->tmpfiles as $fname ) {
186 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
187 unlink( $fname );
188 } elseif ( is_dir( $fname ) ) {
189 wfRecursiveRemoveDir( $fname );
193 if ( $this->needsDB() && $this->db ) {
194 // Clean up open transactions
195 while ( $this->db->trxLevel() > 0 ) {
196 $this->db->rollback();
199 // don't ignore DB errors
200 $this->db->ignoreErrors( false );
203 wfProfileOut( __METHOD__ );
206 protected function tearDown() {
207 wfProfileIn( __METHOD__ );
209 // Cleaning up temporary files
210 foreach ( $this->tmpfiles as $fname ) {
211 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
212 unlink( $fname );
213 } elseif ( is_dir( $fname ) ) {
214 wfRecursiveRemoveDir( $fname );
218 if ( $this->needsDB() && $this->db ) {
219 // Clean up open transactions
220 while ( $this->db->trxLevel() > 0 ) {
221 $this->db->rollback();
224 // don't ignore DB errors
225 $this->db->ignoreErrors( false );
228 // Restore mw globals
229 foreach ( $this->mwGlobals as $key => $value ) {
230 $GLOBALS[$key] = $value;
232 $this->mwGlobals = array();
234 parent::tearDown();
235 wfProfileOut( __METHOD__ );
239 * Make sure MediaWikiTestCase extending classes have called their
240 * parent setUp method
242 final public function testMediaWikiTestCaseParentSetupCalled() {
243 $this->assertArrayHasKey( 'setUp', $this->called,
244 get_called_class() . "::setUp() must call parent::setUp()"
249 * Individual test functions may override globals (either directly or through this
250 * setMwGlobals() function), however one must call this method at least once for
251 * each key within the setUp().
252 * That way the key is added to the array of globals that will be reset afterwards
253 * in the tearDown(). And, equally important, that way all other tests are executed
254 * with the same settings (instead of using the unreliable local settings for most
255 * tests and fix it only for some tests).
257 * @example
258 * <code>
259 * protected function setUp() {
260 * $this->setMwGlobals( 'wgRestrictStuff', true );
263 * function testFoo() {}
265 * function testBar() {}
266 * $this->assertTrue( self::getX()->doStuff() );
268 * $this->setMwGlobals( 'wgRestrictStuff', false );
269 * $this->assertTrue( self::getX()->doStuff() );
272 * function testQuux() {}
273 * </code>
275 * @param array|string $pairs Key to the global variable, or an array
276 * of key/value pairs.
277 * @param mixed $value Value to set the global to (ignored
278 * if an array is given as first argument).
280 protected function setMwGlobals( $pairs, $value = null ) {
282 // Normalize (string, value) to an array
283 if ( is_string( $pairs ) ) {
284 $pairs = array( $pairs => $value );
287 foreach ( $pairs as $key => $value ) {
288 // NOTE: make sure we only save the global once or a second call to
289 // setMwGlobals() on the same global would override the original
290 // value.
291 if ( !array_key_exists( $key, $this->mwGlobals ) ) {
292 $this->mwGlobals[$key] = $GLOBALS[$key];
295 // Override the global
296 $GLOBALS[$key] = $value;
301 * Merges the given values into a MW global array variable.
302 * Useful for setting some entries in a configuration array, instead of
303 * setting the entire array.
305 * @param String $name The name of the global, as in wgFooBar
306 * @param Array $values The array containing the entries to set in that global
308 * @throws MWException if the designated global is not an array.
310 protected function mergeMwGlobalArrayValue( $name, $values ) {
311 if ( !isset( $GLOBALS[$name] ) ) {
312 $merged = $values;
313 } else {
314 if ( !is_array( $GLOBALS[$name] ) ) {
315 throw new MWException( "MW global $name is not an array." );
318 // NOTE: do not use array_merge, it screws up for numeric keys.
319 $merged = $GLOBALS[$name];
320 foreach ( $values as $k => $v ) {
321 $merged[$k] = $v;
325 $this->setMwGlobals( $name, $merged );
328 function dbPrefix() {
329 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
332 function needsDB() {
333 # if the test says it uses database tables, it needs the database
334 if ( $this->tablesUsed ) {
335 return true;
338 # if the test says it belongs to the Database group, it needs the database
339 $rc = new ReflectionClass( $this );
340 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
341 return true;
344 return false;
348 * Stub. If a test needs to add additional data to the database, it should
349 * implement this method and do so
351 function addDBData() {}
353 private function addCoreDBData() {
354 # disabled for performance
355 #$this->tablesUsed[] = 'page';
356 #$this->tablesUsed[] = 'revision';
358 if ( $this->db->getType() == 'oracle' ) {
360 # Insert 0 user to prevent FK violations
361 # Anonymous user
362 $this->db->insert( 'user', array(
363 'user_id' => 0,
364 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
366 # Insert 0 page to prevent FK violations
367 # Blank page
368 $this->db->insert( 'page', array(
369 'page_id' => 0,
370 'page_namespace' => 0,
371 'page_title' => ' ',
372 'page_restrictions' => null,
373 'page_counter' => 0,
374 'page_is_redirect' => 0,
375 'page_is_new' => 0,
376 'page_random' => 0,
377 'page_touched' => $this->db->timestamp(),
378 'page_latest' => 0,
379 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
383 User::resetIdByNameCache();
385 //Make sysop user
386 $user = User::newFromName( 'UTSysop' );
388 if ( $user->idForName() == 0 ) {
389 $user->addToDatabase();
390 $user->setPassword( 'UTSysopPassword' );
392 $user->addGroup( 'sysop' );
393 $user->addGroup( 'bureaucrat' );
394 $user->saveSettings();
398 //Make 1 page with 1 revision
399 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
400 if ( !$page->getId() == 0 ) {
401 $page->doEditContent(
402 new WikitextContent( 'UTContent' ),
403 'UTPageSummary',
404 EDIT_NEW,
405 false,
406 User::newFromName( 'UTSysop' ) );
411 * Restores MediaWiki to using the table set (table prefix) it was using before
412 * setupTestDB() was called. Useful if we need to perform database operations
413 * after the test run has finished (such as saving logs or profiling info).
415 public static function teardownTestDB() {
416 if ( !self::$dbSetup ) {
417 return;
420 CloneDatabase::changePrefix( self::$oldTablePrefix );
422 self::$oldTablePrefix = false;
423 self::$dbSetup = false;
427 * Creates an empty skeleton of the wiki database by cloning its structure
428 * to equivalent tables using the given $prefix. Then sets MediaWiki to
429 * use the new set of tables (aka schema) instead of the original set.
431 * This is used to generate a dummy table set, typically consisting of temporary
432 * tables, that will be used by tests instead of the original wiki database tables.
434 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
435 * by teardownTestDB() to return the wiki to using the original table set.
437 * @note: this method only works when first called. Subsequent calls have no effect,
438 * even if using different parameters.
440 * @param DatabaseBase $db The database connection
441 * @param String $prefix The prefix to use for the new table set (aka schema).
443 * @throws MWException if the database table prefix is already $prefix
445 public static function setupTestDB( DatabaseBase $db, $prefix ) {
446 global $wgDBprefix;
447 if ( $wgDBprefix === $prefix ) {
448 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
451 if ( self::$dbSetup ) {
452 return;
455 $tablesCloned = self::listTables( $db );
456 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
457 $dbClone->useTemporaryTables( self::$useTemporaryTables );
459 self::$dbSetup = true;
460 self::$oldTablePrefix = $wgDBprefix;
462 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
463 CloneDatabase::changePrefix( $prefix );
464 return;
465 } else {
466 $dbClone->cloneTableStructure();
469 if ( $db->getType() == 'oracle' ) {
470 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
475 * Empty all tables so they can be repopulated for tests
477 private function resetDB() {
478 if ( $this->db ) {
479 if ( $this->db->getType() == 'oracle' ) {
480 if ( self::$useTemporaryTables ) {
481 wfGetLB()->closeAll();
482 $this->db = wfGetDB( DB_MASTER );
483 } else {
484 foreach ( $this->tablesUsed as $tbl ) {
485 if ( $tbl == 'interwiki' ) {
486 continue;
488 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
491 } else {
492 foreach ( $this->tablesUsed as $tbl ) {
493 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
494 continue;
496 $this->db->delete( $tbl, '*', __METHOD__ );
502 function __call( $func, $args ) {
503 static $compatibility = array(
504 'assertInternalType' => 'assertType',
505 'assertNotInternalType' => 'assertNotType',
506 'assertInstanceOf' => 'assertType',
507 'assertEmpty' => 'assertEmpty2',
510 if ( method_exists( $this->suite, $func ) ) {
511 return call_user_func_array( array( $this->suite, $func ), $args );
512 } elseif ( isset( $compatibility[$func] ) ) {
513 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
514 } else {
515 throw new MWException( "Called non-existant $func method on "
516 . get_class( $this ) );
520 private function assertEmpty2( $value, $msg ) {
521 return $this->assertTrue( $value == '', $msg );
524 private static function unprefixTable( $tableName ) {
525 global $wgDBprefix;
526 return substr( $tableName, strlen( $wgDBprefix ) );
529 private static function isNotUnittest( $table ) {
530 return strpos( $table, 'unittest_' ) !== 0;
533 public static function listTables( $db ) {
534 global $wgDBprefix;
536 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
537 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
539 // Don't duplicate test tables from the previous fataled run
540 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
542 if ( $db->getType() == 'sqlite' ) {
543 $tables = array_flip( $tables );
544 // these are subtables of searchindex and don't need to be duped/dropped separately
545 unset( $tables['searchindex_content'] );
546 unset( $tables['searchindex_segdir'] );
547 unset( $tables['searchindex_segments'] );
548 $tables = array_flip( $tables );
550 return $tables;
553 protected function checkDbIsSupported() {
554 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
555 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
559 public function getCliArg( $offset ) {
561 if ( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
562 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
567 public function setCliArg( $offset, $value ) {
569 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
574 * Don't throw a warning if $function is deprecated and called later
576 * @param $function String
577 * @return null
579 function hideDeprecated( $function ) {
580 wfSuppressWarnings();
581 wfDeprecated( $function );
582 wfRestoreWarnings();
586 * Asserts that the given database query yields the rows given by $expectedRows.
587 * The expected rows should be given as indexed (not associative) arrays, with
588 * the values given in the order of the columns in the $fields parameter.
589 * Note that the rows are sorted by the columns given in $fields.
591 * @since 1.20
593 * @param $table String|Array the table(s) to query
594 * @param $fields String|Array the columns to include in the result (and to sort by)
595 * @param $condition String|Array "where" condition(s)
596 * @param $expectedRows Array - an array of arrays giving the expected rows.
598 * @throws MWException if this test cases's needsDB() method doesn't return true.
599 * Test cases can use "@group Database" to enable database test support,
600 * or list the tables under testing in $this->tablesUsed, or override the
601 * needsDB() method.
603 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
604 if ( !$this->needsDB() ) {
605 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
606 ' method should return true. Use @group Database or $this->tablesUsed.' );
609 $db = wfGetDB( DB_SLAVE );
611 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
612 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
614 $i = 0;
616 foreach ( $expectedRows as $expected ) {
617 $r = $res->fetchRow();
618 self::stripStringKeys( $r );
620 $i += 1;
621 $this->assertNotEmpty( $r, "row #$i missing" );
623 $this->assertEquals( $expected, $r, "row #$i mismatches" );
626 $r = $res->fetchRow();
627 self::stripStringKeys( $r );
629 $this->assertFalse( $r, "found extra row (after #$i)" );
633 * Utility method taking an array of elements and wrapping
634 * each element in it's own array. Useful for data providers
635 * that only return a single argument.
637 * @since 1.20
639 * @param array $elements
641 * @return array
643 protected function arrayWrap( array $elements ) {
644 return array_map(
645 function ( $element ) {
646 return array( $element );
648 $elements
653 * Assert that two arrays are equal. By default this means that both arrays need to hold
654 * the same set of values. Using additional arguments, order and associated key can also
655 * be set as relevant.
657 * @since 1.20
659 * @param array $expected
660 * @param array $actual
661 * @param boolean $ordered If the order of the values should match
662 * @param boolean $named If the keys should match
664 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
665 if ( !$ordered ) {
666 $this->objectAssociativeSort( $expected );
667 $this->objectAssociativeSort( $actual );
670 if ( !$named ) {
671 $expected = array_values( $expected );
672 $actual = array_values( $actual );
675 call_user_func_array(
676 array( $this, 'assertEquals' ),
677 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
682 * Put each HTML element on its own line and then equals() the results
684 * Use for nicely formatting of PHPUnit diff output when comparing very
685 * simple HTML
687 * @since 1.20
689 * @param String $expected HTML on oneline
690 * @param String $actual HTML on oneline
691 * @param String $msg Optional message
693 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
694 $expected = str_replace( '>', ">\n", $expected );
695 $actual = str_replace( '>', ">\n", $actual );
697 $this->assertEquals( $expected, $actual, $msg );
701 * Does an associative sort that works for objects.
703 * @since 1.20
705 * @param array $array
707 protected function objectAssociativeSort( array &$array ) {
708 uasort(
709 $array,
710 function ( $a, $b ) {
711 return serialize( $a ) > serialize( $b ) ? 1 : -1;
717 * Utility function for eliminating all string keys from an array.
718 * Useful to turn a database result row as returned by fetchRow() into
719 * a pure indexed array.
721 * @since 1.20
723 * @param $r mixed the array to remove string keys from.
725 protected static function stripStringKeys( &$r ) {
726 if ( !is_array( $r ) ) {
727 return;
730 foreach ( $r as $k => $v ) {
731 if ( is_string( $k ) ) {
732 unset( $r[$k] );
738 * Asserts that the provided variable is of the specified
739 * internal type or equals the $value argument. This is useful
740 * for testing return types of functions that return a certain
741 * type or *value* when not set or on error.
743 * @since 1.20
745 * @param string $type
746 * @param mixed $actual
747 * @param mixed $value
748 * @param string $message
750 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
751 if ( $actual === $value ) {
752 $this->assertTrue( true, $message );
753 } else {
754 $this->assertType( $type, $actual, $message );
759 * Asserts the type of the provided value. This can be either
760 * in internal type such as boolean or integer, or a class or
761 * interface the value extends or implements.
763 * @since 1.20
765 * @param string $type
766 * @param mixed $actual
767 * @param string $message
769 protected function assertType( $type, $actual, $message = '' ) {
770 if ( class_exists( $type ) || interface_exists( $type ) ) {
771 $this->assertInstanceOf( $type, $actual, $message );
772 } else {
773 $this->assertInternalType( $type, $actual, $message );
778 * Returns true iff the given namespace defaults to Wikitext
779 * according to $wgNamespaceContentModels
781 * @param int $ns The namespace ID to check
783 * @return bool
784 * @since 1.21
786 protected function isWikitextNS( $ns ) {
787 global $wgNamespaceContentModels;
789 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
790 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
793 return true;
797 * Returns the ID of a namespace that defaults to Wikitext.
798 * Throws an MWException if there is none.
800 * @return int the ID of the wikitext Namespace
801 * @since 1.21
803 protected function getDefaultWikitextNS() {
804 global $wgNamespaceContentModels;
806 static $wikitextNS = null; // this is not going to change
807 if ( $wikitextNS !== null ) {
808 return $wikitextNS;
811 // quickly short out on most common case:
812 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
813 return NS_MAIN;
816 // NOTE: prefer content namespaces
817 $namespaces = array_unique( array_merge(
818 MWNamespace::getContentNamespaces(),
819 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
820 MWNamespace::getValidNamespaces()
821 ) );
823 $namespaces = array_diff( $namespaces, array(
824 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
825 ) );
827 $talk = array_filter( $namespaces, function ( $ns ) {
828 return MWNamespace::isTalk( $ns );
829 } );
831 // prefer non-talk pages
832 $namespaces = array_diff( $namespaces, $talk );
833 $namespaces = array_merge( $namespaces, $talk );
835 // check default content model of each namespace
836 foreach ( $namespaces as $ns ) {
837 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
838 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
841 $wikitextNS = $ns;
842 return $wikitextNS;
846 // give up
847 // @todo: Inside a test, we could skip the test as incomplete.
848 // But frequently, this is used in fixture setup.
849 throw new MWException( "No namespace defaults to wikitext!" );
853 * Check, if $wgDiff3 is set and ready to merge
854 * Will mark the calling test as skipped, if not ready
856 * @since 1.21
858 protected function checkHasDiff3() {
859 global $wgDiff3;
861 # This check may also protect against code injection in
862 # case of broken installations.
863 wfSuppressWarnings();
864 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
865 wfRestoreWarnings();
867 if ( !$haveDiff3 ) {
868 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
873 * Check whether we have the 'gzip' commandline utility, will skip
874 * the test whenever "gzip -V" fails.
876 * Result is cached at the process level.
878 * @return bool
880 * @since 1.21
882 protected function checkHasGzip() {
883 static $haveGzip;
885 if ( $haveGzip === null ) {
886 $retval = null;
887 wfShellExec( 'gzip -V', $retval );
888 $haveGzip = ( $retval === 0 );
891 if ( !$haveGzip ) {
892 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
895 return $haveGzip;
899 * Check if $extName is a loaded PHP extension, will skip the
900 * test whenever it is not loaded.
902 * @since 1.21
904 protected function checkPHPExtension( $extName ) {
905 $loaded = extension_loaded( $extName );
906 if ( !$loaded ) {
907 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
909 return $loaded;
913 * Asserts that an exception of the specified type occurs when running
914 * the provided code.
916 * @since 1.21
918 * @param callable $code
919 * @param string $expected
920 * @param string $message
922 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
923 $pokemons = null;
925 try {
926 call_user_func( $code );
927 } catch ( Exception $pokemons ) {
928 // Gotta Catch 'Em All!
931 if ( $message === '' ) {
932 $message = 'An exception of type "' . $expected . '" should have been thrown';
935 $this->assertInstanceOf( $expected, $pokemons, $message );