Merge "Add type hint against LinkTarget"
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2 use MediaWiki\Logger\LegacySpi;
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\MonologSpi;
5 use Psr\Log\LoggerInterface;
6
7 /**
8 * @since 1.18
9 */
10 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
11 /**
12 * $called tracks whether the setUp and tearDown method has been called.
13 * class extending MediaWikiTestCase usually override setUp and tearDown
14 * but forget to call the parent.
15 *
16 * The array format takes a method name as key and anything as a value.
17 * By asserting the key exist, we know the child class has called the
18 * parent.
19 *
20 * This property must be private, we do not want child to override it,
21 * they should call the appropriate parent method instead.
22 */
23 private $called = [];
24
25 /**
26 * @var TestUser[]
27 * @since 1.20
28 */
29 public static $users;
30
31 /**
32 * @var DatabaseBase
33 * @since 1.18
34 */
35 protected $db;
36
37 /**
38 * @var array
39 * @since 1.19
40 */
41 protected $tablesUsed = []; // tables with data
42
43 private static $useTemporaryTables = true;
44 private static $reuseDB = false;
45 private static $dbSetup = false;
46 private static $oldTablePrefix = false;
47
48 /**
49 * Original value of PHP's error_reporting setting.
50 *
51 * @var int
52 */
53 private $phpErrorLevel;
54
55 /**
56 * Holds the paths of temporary files/directories created through getNewTempFile,
57 * and getNewTempDirectory
58 *
59 * @var array
60 */
61 private $tmpFiles = [];
62
63 /**
64 * Holds original values of MediaWiki configuration settings
65 * to be restored in tearDown().
66 * See also setMwGlobals().
67 * @var array
68 */
69 private $mwGlobals = [];
70
71 /**
72 * Holds original loggers which have been replaced by setLogger()
73 * @var LoggerInterface[]
74 */
75 private $loggers = [];
76
77 /**
78 * Table name prefixes. Oracle likes it shorter.
79 */
80 const DB_PREFIX = 'unittest_';
81 const ORA_DB_PREFIX = 'ut_';
82
83 /**
84 * @var array
85 * @since 1.18
86 */
87 protected $supportedDBs = [
88 'mysql',
89 'sqlite',
90 'postgres',
91 'oracle'
92 ];
93
94 public function __construct( $name = null, array $data = [], $dataName = '' ) {
95 parent::__construct( $name, $data, $dataName );
96
97 $this->backupGlobals = false;
98 $this->backupStaticAttributes = false;
99 }
100
101 public function __destruct() {
102 // Complain if self::setUp() was called, but not self::tearDown()
103 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
104 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
105 throw new MWException( get_called_class() . "::tearDown() must call parent::tearDown()" );
106 }
107 }
108
109 public function run( PHPUnit_Framework_TestResult $result = null ) {
110 /* Some functions require some kind of caching, and will end up using the db,
111 * which we can't allow, as that would open a new connection for mysql.
112 * Replace with a HashBag. They would not be going to persist anyway.
113 */
114 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
115
116 // Sandbox APC by replacing with in-process hash instead.
117 // Ensures values are removed between tests.
118 ObjectCache::$instances['apc'] =
119 ObjectCache::$instances['xcache'] =
120 ObjectCache::$instances['wincache'] = new HashBagOStuff;
121
122 $needsResetDB = false;
123
124 if ( $this->needsDB() ) {
125 // set up a DB connection for this test to use
126
127 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
128 self::$reuseDB = $this->getCliArg( 'reuse-db' );
129
130 $this->db = wfGetDB( DB_MASTER );
131
132 $this->checkDbIsSupported();
133
134 if ( !self::$dbSetup ) {
135 // switch to a temporary clone of the database
136 self::setupTestDB( $this->db, $this->dbPrefix() );
137
138 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
139 $this->resetDB();
140 }
141 }
142 $this->addCoreDBData();
143 $this->addDBData();
144 $needsResetDB = true;
145 }
146
147 parent::run( $result );
148
149 if ( $needsResetDB ) {
150 $this->resetDB();
151 }
152 }
153
154 /**
155 * @since 1.21
156 *
157 * @return bool
158 */
159 public function usesTemporaryTables() {
160 return self::$useTemporaryTables;
161 }
162
163 /**
164 * Obtains a new temporary file name
165 *
166 * The obtained filename is enlisted to be removed upon tearDown
167 *
168 * @since 1.20
169 *
170 * @return string Absolute name of the temporary file
171 */
172 protected function getNewTempFile() {
173 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
174 $this->tmpFiles[] = $fileName;
175
176 return $fileName;
177 }
178
179 /**
180 * obtains a new temporary directory
181 *
182 * The obtained directory is enlisted to be removed (recursively with all its contained
183 * files) upon tearDown.
184 *
185 * @since 1.20
186 *
187 * @return string Absolute name of the temporary directory
188 */
189 protected function getNewTempDirectory() {
190 // Starting of with a temporary /file/.
191 $fileName = $this->getNewTempFile();
192
193 // Converting the temporary /file/ to a /directory/
194 // The following is not atomic, but at least we now have a single place,
195 // where temporary directory creation is bundled and can be improved
196 unlink( $fileName );
197 $this->assertTrue( wfMkdirParents( $fileName ) );
198
199 return $fileName;
200 }
201
202 protected function setUp() {
203 parent::setUp();
204 $this->called['setUp'] = true;
205
206 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
207
208 // Cleaning up temporary files
209 foreach ( $this->tmpFiles as $fileName ) {
210 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
211 unlink( $fileName );
212 } elseif ( is_dir( $fileName ) ) {
213 wfRecursiveRemoveDir( $fileName );
214 }
215 }
216
217 if ( $this->needsDB() && $this->db ) {
218 // Clean up open transactions
219 while ( $this->db->trxLevel() > 0 ) {
220 $this->db->rollback( __METHOD__, 'flush' );
221 }
222 }
223
224 DeferredUpdates::clearPendingUpdates();
225
226 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
227 }
228
229 protected function addTmpFiles( $files ) {
230 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
231 }
232
233 protected function tearDown() {
234 global $wgRequest;
235
236 $status = ob_get_status();
237 if ( isset( $status['name'] ) &&
238 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
239 ) {
240 ob_end_flush();
241 }
242
243 $this->called['tearDown'] = true;
244 // Cleaning up temporary files
245 foreach ( $this->tmpFiles as $fileName ) {
246 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
247 unlink( $fileName );
248 } elseif ( is_dir( $fileName ) ) {
249 wfRecursiveRemoveDir( $fileName );
250 }
251 }
252
253 if ( $this->needsDB() && $this->db ) {
254 // Clean up open transactions
255 while ( $this->db->trxLevel() > 0 ) {
256 $this->db->rollback( __METHOD__, 'flush' );
257 }
258 }
259
260 // Restore mw globals
261 foreach ( $this->mwGlobals as $key => $value ) {
262 $GLOBALS[$key] = $value;
263 }
264 $this->mwGlobals = [];
265 $this->restoreLoggers();
266 RequestContext::resetMain();
267 MediaHandler::resetCache();
268 if ( session_id() !== '' ) {
269 session_write_close();
270 session_id( '' );
271 }
272 $wgRequest = new FauxRequest();
273 MediaWiki\Session\SessionManager::resetCache();
274
275 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
276
277 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
278 ini_set( 'error_reporting', $this->phpErrorLevel );
279
280 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
281 $newHex = strtoupper( dechex( $phpErrorLevel ) );
282 $message = "PHP error_reporting setting was left dirty: "
283 . "was 0x$oldHex before test, 0x$newHex after test!";
284
285 $this->fail( $message );
286 }
287
288 parent::tearDown();
289 }
290
291 /**
292 * Make sure MediaWikiTestCase extending classes have called their
293 * parent setUp method
294 */
295 final public function testMediaWikiTestCaseParentSetupCalled() {
296 $this->assertArrayHasKey( 'setUp', $this->called,
297 get_called_class() . "::setUp() must call parent::setUp()"
298 );
299 }
300
301 /**
302 * Sets a global, maintaining a stashed version of the previous global to be
303 * restored in tearDown
304 *
305 * The key is added to the array of globals that will be reset afterwards
306 * in the tearDown().
307 *
308 * @example
309 * <code>
310 * protected function setUp() {
311 * $this->setMwGlobals( 'wgRestrictStuff', true );
312 * }
313 *
314 * function testFoo() {}
315 *
316 * function testBar() {}
317 * $this->assertTrue( self::getX()->doStuff() );
318 *
319 * $this->setMwGlobals( 'wgRestrictStuff', false );
320 * $this->assertTrue( self::getX()->doStuff() );
321 * }
322 *
323 * function testQuux() {}
324 * </code>
325 *
326 * @param array|string $pairs Key to the global variable, or an array
327 * of key/value pairs.
328 * @param mixed $value Value to set the global to (ignored
329 * if an array is given as first argument).
330 *
331 * @since 1.21
332 */
333 protected function setMwGlobals( $pairs, $value = null ) {
334 if ( is_string( $pairs ) ) {
335 $pairs = [ $pairs => $value ];
336 }
337
338 $this->stashMwGlobals( array_keys( $pairs ) );
339
340 foreach ( $pairs as $key => $value ) {
341 $GLOBALS[$key] = $value;
342 }
343 }
344
345 /**
346 * Stashes the global, will be restored in tearDown()
347 *
348 * Individual test functions may override globals through the setMwGlobals() function
349 * or directly. When directly overriding globals their keys should first be passed to this
350 * method in setUp to avoid breaking global state for other tests
351 *
352 * That way all other tests are executed with the same settings (instead of using the
353 * unreliable local settings for most tests and fix it only for some tests).
354 *
355 * @param array|string $globalKeys Key to the global variable, or an array of keys.
356 *
357 * @throws Exception When trying to stash an unset global
358 * @since 1.23
359 */
360 protected function stashMwGlobals( $globalKeys ) {
361 if ( is_string( $globalKeys ) ) {
362 $globalKeys = [ $globalKeys ];
363 }
364
365 foreach ( $globalKeys as $globalKey ) {
366 // NOTE: make sure we only save the global once or a second call to
367 // setMwGlobals() on the same global would override the original
368 // value.
369 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
370 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
371 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
372 }
373 // NOTE: we serialize then unserialize the value in case it is an object
374 // this stops any objects being passed by reference. We could use clone
375 // and if is_object but this does account for objects within objects!
376 try {
377 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
378 }
379 // NOTE; some things such as Closures are not serializable
380 // in this case just set the value!
381 catch ( Exception $e ) {
382 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
383 }
384 }
385 }
386 }
387
388 /**
389 * Merges the given values into a MW global array variable.
390 * Useful for setting some entries in a configuration array, instead of
391 * setting the entire array.
392 *
393 * @param string $name The name of the global, as in wgFooBar
394 * @param array $values The array containing the entries to set in that global
395 *
396 * @throws MWException If the designated global is not an array.
397 *
398 * @since 1.21
399 */
400 protected function mergeMwGlobalArrayValue( $name, $values ) {
401 if ( !isset( $GLOBALS[$name] ) ) {
402 $merged = $values;
403 } else {
404 if ( !is_array( $GLOBALS[$name] ) ) {
405 throw new MWException( "MW global $name is not an array." );
406 }
407
408 // NOTE: do not use array_merge, it screws up for numeric keys.
409 $merged = $GLOBALS[$name];
410 foreach ( $values as $k => $v ) {
411 $merged[$k] = $v;
412 }
413 }
414
415 $this->setMwGlobals( $name, $merged );
416 }
417
418 /**
419 * Sets the logger for a specified channel, for the duration of the test.
420 * @since 1.27
421 * @param string $channel
422 * @param LoggerInterface $logger
423 */
424 protected function setLogger( $channel, LoggerInterface $logger ) {
425 $provider = LoggerFactory::getProvider();
426 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
427 $singletons = $wrappedProvider->singletons;
428 if ( $provider instanceof MonologSpi ) {
429 if ( !isset( $this->loggers[$channel] ) ) {
430 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
431 ? $singletons['loggers'][$channel] : null;
432 }
433 $singletons['loggers'][$channel] = $logger;
434 } elseif ( $provider instanceof LegacySpi ) {
435 if ( !isset( $this->loggers[$channel] ) ) {
436 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
437 }
438 $singletons[$channel] = $logger;
439 } else {
440 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
441 . ' is not implemented' );
442 }
443 $wrappedProvider->singletons = $singletons;
444 }
445
446 /**
447 * Restores loggers replaced by setLogger().
448 * @since 1.27
449 */
450 private function restoreLoggers() {
451 $provider = LoggerFactory::getProvider();
452 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
453 $singletons = $wrappedProvider->singletons;
454 foreach ( $this->loggers as $channel => $logger ) {
455 if ( $provider instanceof MonologSpi ) {
456 if ( $logger === null ) {
457 unset( $singletons['loggers'][$channel] );
458 } else {
459 $singletons['loggers'][$channel] = $logger;
460 }
461 } elseif ( $provider instanceof LegacySpi ) {
462 if ( $logger === null ) {
463 unset( $singletons[$channel] );
464 } else {
465 $singletons[$channel] = $logger;
466 }
467 }
468 }
469 $wrappedProvider->singletons = $singletons;
470 $this->loggers = [];
471 }
472
473 /**
474 * @return string
475 * @since 1.18
476 */
477 public function dbPrefix() {
478 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
479 }
480
481 /**
482 * @return bool
483 * @since 1.18
484 */
485 public function needsDB() {
486 # if the test says it uses database tables, it needs the database
487 if ( $this->tablesUsed ) {
488 return true;
489 }
490
491 # if the test says it belongs to the Database group, it needs the database
492 $rc = new ReflectionClass( $this );
493 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
494 return true;
495 }
496
497 return false;
498 }
499
500 /**
501 * Insert a new page.
502 *
503 * Should be called from addDBData().
504 *
505 * @since 1.25
506 * @param string $pageName Page name
507 * @param string $text Page's content
508 * @return array Title object and page id
509 */
510 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
511 $title = Title::newFromText( $pageName, 0 );
512
513 $user = User::newFromName( 'UTSysop' );
514 $comment = __METHOD__ . ': Sample page for unit test.';
515
516 // Avoid memory leak...?
517 // LinkCache::singleton()->clear();
518 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
519
520 $page = WikiPage::factory( $title );
521 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
522
523 return [
524 'title' => $title,
525 'id' => $page->getId(),
526 ];
527 }
528
529 /**
530 * Stub. If a test needs to add additional data to the database, it should
531 * implement this method and do so
532 *
533 * @since 1.18
534 */
535 public function addDBData() {
536 }
537
538 private function addCoreDBData() {
539 if ( $this->db->getType() == 'oracle' ) {
540
541 # Insert 0 user to prevent FK violations
542 # Anonymous user
543 $this->db->insert( 'user', [
544 'user_id' => 0,
545 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
546
547 # Insert 0 page to prevent FK violations
548 # Blank page
549 $this->db->insert( 'page', [
550 'page_id' => 0,
551 'page_namespace' => 0,
552 'page_title' => ' ',
553 'page_restrictions' => null,
554 'page_is_redirect' => 0,
555 'page_is_new' => 0,
556 'page_random' => 0,
557 'page_touched' => $this->db->timestamp(),
558 'page_latest' => 0,
559 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
560 }
561
562 User::resetIdByNameCache();
563
564 // Make sysop user
565 $user = User::newFromName( 'UTSysop' );
566
567 if ( $user->idForName() == 0 ) {
568 $user->addToDatabase();
569 TestUser::setPasswordForUser( $user, 'UTSysopPassword' );
570 }
571
572 // Always set groups, because $this->resetDB() wipes them out
573 $user->addGroup( 'sysop' );
574 $user->addGroup( 'bureaucrat' );
575
576 // Make 1 page with 1 revision
577 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
578 if ( $page->getId() == 0 ) {
579 $page->doEditContent(
580 new WikitextContent( 'UTContent' ),
581 'UTPageSummary',
582 EDIT_NEW,
583 false,
584 $user
585 );
586
587 // doEditContent() probably started the session via
588 // User::loadFromSession(). Close it now.
589 if ( session_id() !== '' ) {
590 session_write_close();
591 session_id( '' );
592 }
593 }
594 }
595
596 /**
597 * Restores MediaWiki to using the table set (table prefix) it was using before
598 * setupTestDB() was called. Useful if we need to perform database operations
599 * after the test run has finished (such as saving logs or profiling info).
600 *
601 * @since 1.21
602 */
603 public static function teardownTestDB() {
604 global $wgJobClasses;
605
606 if ( !self::$dbSetup ) {
607 return;
608 }
609
610 foreach ( $wgJobClasses as $type => $class ) {
611 // Delete any jobs under the clone DB (or old prefix in other stores)
612 JobQueueGroup::singleton()->get( $type )->delete();
613 }
614
615 CloneDatabase::changePrefix( self::$oldTablePrefix );
616
617 self::$oldTablePrefix = false;
618 self::$dbSetup = false;
619 }
620
621 /**
622 * Creates an empty skeleton of the wiki database by cloning its structure
623 * to equivalent tables using the given $prefix. Then sets MediaWiki to
624 * use the new set of tables (aka schema) instead of the original set.
625 *
626 * This is used to generate a dummy table set, typically consisting of temporary
627 * tables, that will be used by tests instead of the original wiki database tables.
628 *
629 * @since 1.21
630 *
631 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
632 * by teardownTestDB() to return the wiki to using the original table set.
633 *
634 * @note this method only works when first called. Subsequent calls have no effect,
635 * even if using different parameters.
636 *
637 * @param DatabaseBase $db The database connection
638 * @param string $prefix The prefix to use for the new table set (aka schema).
639 *
640 * @throws MWException If the database table prefix is already $prefix
641 */
642 public static function setupTestDB( DatabaseBase $db, $prefix ) {
643 global $wgDBprefix;
644 if ( $wgDBprefix === $prefix ) {
645 throw new MWException(
646 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
647 }
648
649 if ( self::$dbSetup ) {
650 return;
651 }
652
653 $tablesCloned = self::listTables( $db );
654 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
655 $dbClone->useTemporaryTables( self::$useTemporaryTables );
656
657 self::$dbSetup = true;
658 self::$oldTablePrefix = $wgDBprefix;
659
660 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
661 CloneDatabase::changePrefix( $prefix );
662
663 return;
664 } else {
665 $dbClone->cloneTableStructure();
666 }
667
668 if ( $db->getType() == 'oracle' ) {
669 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
670 }
671 }
672
673 /**
674 * Empty all tables so they can be repopulated for tests
675 */
676 private function resetDB() {
677 if ( $this->db ) {
678 if ( $this->db->getType() == 'oracle' ) {
679 if ( self::$useTemporaryTables ) {
680 wfGetLB()->closeAll();
681 $this->db = wfGetDB( DB_MASTER );
682 } else {
683 foreach ( $this->tablesUsed as $tbl ) {
684 if ( $tbl == 'interwiki' ) {
685 continue;
686 }
687 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
688 }
689 }
690 } else {
691 foreach ( $this->tablesUsed as $tbl ) {
692 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
693 continue;
694 }
695 $this->db->delete( $tbl, '*', __METHOD__ );
696 }
697 }
698 }
699 }
700
701 /**
702 * @since 1.18
703 *
704 * @param string $func
705 * @param array $args
706 *
707 * @return mixed
708 * @throws MWException
709 */
710 public function __call( $func, $args ) {
711 static $compatibility = [
712 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
713 ];
714
715 if ( isset( $compatibility[$func] ) ) {
716 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
717 } else {
718 throw new MWException( "Called non-existent $func method on "
719 . get_class( $this ) );
720 }
721 }
722
723 /**
724 * Used as a compatibility method for phpunit < 3.7.32
725 * @param string $value
726 * @param string $msg
727 */
728 private function assertEmpty2( $value, $msg ) {
729 $this->assertTrue( $value == '', $msg );
730 }
731
732 private static function unprefixTable( $tableName ) {
733 global $wgDBprefix;
734
735 return substr( $tableName, strlen( $wgDBprefix ) );
736 }
737
738 private static function isNotUnittest( $table ) {
739 return strpos( $table, 'unittest_' ) !== 0;
740 }
741
742 /**
743 * @since 1.18
744 *
745 * @param DatabaseBase $db
746 *
747 * @return array
748 */
749 public static function listTables( $db ) {
750 global $wgDBprefix;
751
752 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
753
754 if ( $db->getType() === 'mysql' ) {
755 # bug 43571: cannot clone VIEWs under MySQL
756 $views = $db->listViews( $wgDBprefix, __METHOD__ );
757 $tables = array_diff( $tables, $views );
758 }
759 $tables = array_map( [ __CLASS__, 'unprefixTable' ], $tables );
760
761 // Don't duplicate test tables from the previous fataled run
762 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
763
764 if ( $db->getType() == 'sqlite' ) {
765 $tables = array_flip( $tables );
766 // these are subtables of searchindex and don't need to be duped/dropped separately
767 unset( $tables['searchindex_content'] );
768 unset( $tables['searchindex_segdir'] );
769 unset( $tables['searchindex_segments'] );
770 $tables = array_flip( $tables );
771 }
772
773 return $tables;
774 }
775
776 /**
777 * @throws MWException
778 * @since 1.18
779 */
780 protected function checkDbIsSupported() {
781 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
782 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
783 }
784 }
785
786 /**
787 * @since 1.18
788 * @param string $offset
789 * @return mixed
790 */
791 public function getCliArg( $offset ) {
792 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
793 return PHPUnitMaintClass::$additionalOptions[$offset];
794 }
795 }
796
797 /**
798 * @since 1.18
799 * @param string $offset
800 * @param mixed $value
801 */
802 public function setCliArg( $offset, $value ) {
803 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
804 }
805
806 /**
807 * Don't throw a warning if $function is deprecated and called later
808 *
809 * @since 1.19
810 *
811 * @param string $function
812 */
813 public function hideDeprecated( $function ) {
814 MediaWiki\suppressWarnings();
815 wfDeprecated( $function );
816 MediaWiki\restoreWarnings();
817 }
818
819 /**
820 * Asserts that the given database query yields the rows given by $expectedRows.
821 * The expected rows should be given as indexed (not associative) arrays, with
822 * the values given in the order of the columns in the $fields parameter.
823 * Note that the rows are sorted by the columns given in $fields.
824 *
825 * @since 1.20
826 *
827 * @param string|array $table The table(s) to query
828 * @param string|array $fields The columns to include in the result (and to sort by)
829 * @param string|array $condition "where" condition(s)
830 * @param array $expectedRows An array of arrays giving the expected rows.
831 *
832 * @throws MWException If this test cases's needsDB() method doesn't return true.
833 * Test cases can use "@group Database" to enable database test support,
834 * or list the tables under testing in $this->tablesUsed, or override the
835 * needsDB() method.
836 */
837 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
838 if ( !$this->needsDB() ) {
839 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
840 ' method should return true. Use @group Database or $this->tablesUsed.' );
841 }
842
843 $db = wfGetDB( DB_SLAVE );
844
845 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
846 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
847
848 $i = 0;
849
850 foreach ( $expectedRows as $expected ) {
851 $r = $res->fetchRow();
852 self::stripStringKeys( $r );
853
854 $i += 1;
855 $this->assertNotEmpty( $r, "row #$i missing" );
856
857 $this->assertEquals( $expected, $r, "row #$i mismatches" );
858 }
859
860 $r = $res->fetchRow();
861 self::stripStringKeys( $r );
862
863 $this->assertFalse( $r, "found extra row (after #$i)" );
864 }
865
866 /**
867 * Utility method taking an array of elements and wrapping
868 * each element in its own array. Useful for data providers
869 * that only return a single argument.
870 *
871 * @since 1.20
872 *
873 * @param array $elements
874 *
875 * @return array
876 */
877 protected function arrayWrap( array $elements ) {
878 return array_map(
879 function ( $element ) {
880 return [ $element ];
881 },
882 $elements
883 );
884 }
885
886 /**
887 * Assert that two arrays are equal. By default this means that both arrays need to hold
888 * the same set of values. Using additional arguments, order and associated key can also
889 * be set as relevant.
890 *
891 * @since 1.20
892 *
893 * @param array $expected
894 * @param array $actual
895 * @param bool $ordered If the order of the values should match
896 * @param bool $named If the keys should match
897 */
898 protected function assertArrayEquals( array $expected, array $actual,
899 $ordered = false, $named = false
900 ) {
901 if ( !$ordered ) {
902 $this->objectAssociativeSort( $expected );
903 $this->objectAssociativeSort( $actual );
904 }
905
906 if ( !$named ) {
907 $expected = array_values( $expected );
908 $actual = array_values( $actual );
909 }
910
911 call_user_func_array(
912 [ $this, 'assertEquals' ],
913 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
914 );
915 }
916
917 /**
918 * Put each HTML element on its own line and then equals() the results
919 *
920 * Use for nicely formatting of PHPUnit diff output when comparing very
921 * simple HTML
922 *
923 * @since 1.20
924 *
925 * @param string $expected HTML on oneline
926 * @param string $actual HTML on oneline
927 * @param string $msg Optional message
928 */
929 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
930 $expected = str_replace( '>', ">\n", $expected );
931 $actual = str_replace( '>', ">\n", $actual );
932
933 $this->assertEquals( $expected, $actual, $msg );
934 }
935
936 /**
937 * Does an associative sort that works for objects.
938 *
939 * @since 1.20
940 *
941 * @param array $array
942 */
943 protected function objectAssociativeSort( array &$array ) {
944 uasort(
945 $array,
946 function ( $a, $b ) {
947 return serialize( $a ) > serialize( $b ) ? 1 : -1;
948 }
949 );
950 }
951
952 /**
953 * Utility function for eliminating all string keys from an array.
954 * Useful to turn a database result row as returned by fetchRow() into
955 * a pure indexed array.
956 *
957 * @since 1.20
958 *
959 * @param mixed $r The array to remove string keys from.
960 */
961 protected static function stripStringKeys( &$r ) {
962 if ( !is_array( $r ) ) {
963 return;
964 }
965
966 foreach ( $r as $k => $v ) {
967 if ( is_string( $k ) ) {
968 unset( $r[$k] );
969 }
970 }
971 }
972
973 /**
974 * Asserts that the provided variable is of the specified
975 * internal type or equals the $value argument. This is useful
976 * for testing return types of functions that return a certain
977 * type or *value* when not set or on error.
978 *
979 * @since 1.20
980 *
981 * @param string $type
982 * @param mixed $actual
983 * @param mixed $value
984 * @param string $message
985 */
986 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
987 if ( $actual === $value ) {
988 $this->assertTrue( true, $message );
989 } else {
990 $this->assertType( $type, $actual, $message );
991 }
992 }
993
994 /**
995 * Asserts the type of the provided value. This can be either
996 * in internal type such as boolean or integer, or a class or
997 * interface the value extends or implements.
998 *
999 * @since 1.20
1000 *
1001 * @param string $type
1002 * @param mixed $actual
1003 * @param string $message
1004 */
1005 protected function assertType( $type, $actual, $message = '' ) {
1006 if ( class_exists( $type ) || interface_exists( $type ) ) {
1007 $this->assertInstanceOf( $type, $actual, $message );
1008 } else {
1009 $this->assertInternalType( $type, $actual, $message );
1010 }
1011 }
1012
1013 /**
1014 * Returns true if the given namespace defaults to Wikitext
1015 * according to $wgNamespaceContentModels
1016 *
1017 * @param int $ns The namespace ID to check
1018 *
1019 * @return bool
1020 * @since 1.21
1021 */
1022 protected function isWikitextNS( $ns ) {
1023 global $wgNamespaceContentModels;
1024
1025 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1026 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1027 }
1028
1029 return true;
1030 }
1031
1032 /**
1033 * Returns the ID of a namespace that defaults to Wikitext.
1034 *
1035 * @throws MWException If there is none.
1036 * @return int The ID of the wikitext Namespace
1037 * @since 1.21
1038 */
1039 protected function getDefaultWikitextNS() {
1040 global $wgNamespaceContentModels;
1041
1042 static $wikitextNS = null; // this is not going to change
1043 if ( $wikitextNS !== null ) {
1044 return $wikitextNS;
1045 }
1046
1047 // quickly short out on most common case:
1048 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1049 return NS_MAIN;
1050 }
1051
1052 // NOTE: prefer content namespaces
1053 $namespaces = array_unique( array_merge(
1054 MWNamespace::getContentNamespaces(),
1055 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1056 MWNamespace::getValidNamespaces()
1057 ) );
1058
1059 $namespaces = array_diff( $namespaces, [
1060 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1061 ] );
1062
1063 $talk = array_filter( $namespaces, function ( $ns ) {
1064 return MWNamespace::isTalk( $ns );
1065 } );
1066
1067 // prefer non-talk pages
1068 $namespaces = array_diff( $namespaces, $talk );
1069 $namespaces = array_merge( $namespaces, $talk );
1070
1071 // check default content model of each namespace
1072 foreach ( $namespaces as $ns ) {
1073 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1074 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1075 ) {
1076
1077 $wikitextNS = $ns;
1078
1079 return $wikitextNS;
1080 }
1081 }
1082
1083 // give up
1084 // @todo Inside a test, we could skip the test as incomplete.
1085 // But frequently, this is used in fixture setup.
1086 throw new MWException( "No namespace defaults to wikitext!" );
1087 }
1088
1089 /**
1090 * Check, if $wgDiff3 is set and ready to merge
1091 * Will mark the calling test as skipped, if not ready
1092 *
1093 * @since 1.21
1094 */
1095 protected function markTestSkippedIfNoDiff3() {
1096 global $wgDiff3;
1097
1098 # This check may also protect against code injection in
1099 # case of broken installations.
1100 MediaWiki\suppressWarnings();
1101 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1102 MediaWiki\restoreWarnings();
1103
1104 if ( !$haveDiff3 ) {
1105 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1106 }
1107 }
1108
1109 /**
1110 * Check whether we have the 'gzip' commandline utility, will skip
1111 * the test whenever "gzip -V" fails.
1112 *
1113 * Result is cached at the process level.
1114 *
1115 * @return bool
1116 *
1117 * @since 1.21
1118 */
1119 protected function checkHasGzip() {
1120 static $haveGzip;
1121
1122 if ( $haveGzip === null ) {
1123 $retval = null;
1124 wfShellExec( 'gzip -V', $retval );
1125 $haveGzip = ( $retval === 0 );
1126 }
1127
1128 if ( !$haveGzip ) {
1129 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1130 }
1131
1132 return $haveGzip;
1133 }
1134
1135 /**
1136 * Check if $extName is a loaded PHP extension, will skip the
1137 * test whenever it is not loaded.
1138 *
1139 * @since 1.21
1140 * @param string $extName
1141 * @return bool
1142 */
1143 protected function checkPHPExtension( $extName ) {
1144 $loaded = extension_loaded( $extName );
1145 if ( !$loaded ) {
1146 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1147 }
1148
1149 return $loaded;
1150 }
1151
1152 /**
1153 * Asserts that an exception of the specified type occurs when running
1154 * the provided code.
1155 *
1156 * @since 1.21
1157 * @deprecated since 1.22 Use setExpectedException
1158 *
1159 * @param callable $code
1160 * @param string $expected
1161 * @param string $message
1162 */
1163 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1164 $pokemons = null;
1165
1166 try {
1167 call_user_func( $code );
1168 } catch ( Exception $pokemons ) {
1169 // Gotta Catch 'Em All!
1170 }
1171
1172 if ( $message === '' ) {
1173 $message = 'An exception of type "' . $expected . '" should have been thrown';
1174 }
1175
1176 $this->assertInstanceOf( $expected, $pokemons, $message );
1177 }
1178
1179 /**
1180 * Asserts that the given string is a valid HTML snippet.
1181 * Wraps the given string in the required top level tags and
1182 * then calls assertValidHtmlDocument().
1183 * The snippet is expected to be HTML 5.
1184 *
1185 * @since 1.23
1186 *
1187 * @note Will mark the test as skipped if the "tidy" module is not installed.
1188 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1189 * when automatic tidying is disabled.
1190 *
1191 * @param string $html An HTML snippet (treated as the contents of the body tag).
1192 */
1193 protected function assertValidHtmlSnippet( $html ) {
1194 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1195 $this->assertValidHtmlDocument( $html );
1196 }
1197
1198 /**
1199 * Asserts that the given string is valid HTML document.
1200 *
1201 * @since 1.23
1202 *
1203 * @note Will mark the test as skipped if the "tidy" module is not installed.
1204 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1205 * when automatic tidying is disabled.
1206 *
1207 * @param string $html A complete HTML document
1208 */
1209 protected function assertValidHtmlDocument( $html ) {
1210 // Note: we only validate if the tidy PHP extension is available.
1211 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1212 // of tidy. In that case however, we can not reliably detect whether a failing validation
1213 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1214 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1215 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1216 $this->markTestSkipped( 'Tidy extension not installed' );
1217 }
1218
1219 $errorBuffer = '';
1220 MWTidy::checkErrors( $html, $errorBuffer );
1221 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1222
1223 // Filter Tidy warnings which aren't useful for us.
1224 // Tidy eg. often cries about parameters missing which have actually
1225 // been deprecated since HTML4, thus we should not care about them.
1226 $errors = preg_grep(
1227 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1228 $allErrors, PREG_GREP_INVERT
1229 );
1230
1231 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1232 }
1233
1234 /**
1235 * @param array $matcher
1236 * @param string $actual
1237 * @param bool $isHtml
1238 *
1239 * @return bool
1240 */
1241 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1242 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1243 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1244 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1245 }
1246
1247 /**
1248 * Note: we are overriding this method to remove the deprecated error
1249 * @see https://phabricator.wikimedia.org/T71505
1250 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1251 * @deprecated
1252 *
1253 * @param array $matcher
1254 * @param string $actual
1255 * @param string $message
1256 * @param bool $isHtml
1257 */
1258 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1259 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1260
1261 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1262 }
1263
1264 /**
1265 * @see MediaWikiTestCase::assertTag
1266 * @deprecated
1267 *
1268 * @param array $matcher
1269 * @param string $actual
1270 * @param string $message
1271 * @param bool $isHtml
1272 */
1273 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1274 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1275
1276 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1277 }
1278
1279 /**
1280 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1281 * @return string
1282 */
1283 public static function wfResetOutputBuffersBarrier( $buffer ) {
1284 return $buffer;
1285 }
1286 }