Ensure disabled deprecation warnings are re-enabled before next test
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 use MediaWiki\Logger\LegacySpi;
4 use MediaWiki\Logger\LoggerFactory;
5 use MediaWiki\Logger\MonologSpi;
6 use MediaWiki\MediaWikiServices;
7 use Psr\Log\LoggerInterface;
8 use Wikimedia\Rdbms\IDatabase;
9 use Wikimedia\Rdbms\IMaintainableDatabase;
10 use Wikimedia\Rdbms\Database;
11 use Wikimedia\TestingAccessWrapper;
12
13 /**
14 * @since 1.18
15 */
16 abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase {
17
18 use MediaWikiCoversValidator;
19 use PHPUnit4And6Compat;
20
21 /**
22 * The original service locator. This is overridden during setUp().
23 *
24 * @var MediaWikiServices|null
25 */
26 private static $originalServices;
27
28 /**
29 * The local service locator, created during setUp().
30 * @var MediaWikiServices
31 */
32 private $localServices;
33
34 /**
35 * $called tracks whether the setUp and tearDown method has been called.
36 * class extending MediaWikiTestCase usually override setUp and tearDown
37 * but forget to call the parent.
38 *
39 * The array format takes a method name as key and anything as a value.
40 * By asserting the key exist, we know the child class has called the
41 * parent.
42 *
43 * This property must be private, we do not want child to override it,
44 * they should call the appropriate parent method instead.
45 */
46 private $called = [];
47
48 /**
49 * @var TestUser[]
50 * @since 1.20
51 */
52 public static $users;
53
54 /**
55 * Primary database
56 *
57 * @var Database
58 * @since 1.18
59 */
60 protected $db;
61
62 /**
63 * @var array
64 * @since 1.19
65 */
66 protected $tablesUsed = []; // tables with data
67
68 private static $useTemporaryTables = true;
69 private static $reuseDB = false;
70 private static $dbSetup = false;
71 private static $oldTablePrefix = '';
72
73 /**
74 * Original value of PHP's error_reporting setting.
75 *
76 * @var int
77 */
78 private $phpErrorLevel;
79
80 /**
81 * Holds the paths of temporary files/directories created through getNewTempFile,
82 * and getNewTempDirectory
83 *
84 * @var array
85 */
86 private $tmpFiles = [];
87
88 /**
89 * Holds original values of MediaWiki configuration settings
90 * to be restored in tearDown().
91 * See also setMwGlobals().
92 * @var array
93 */
94 private $mwGlobals = [];
95
96 /**
97 * Holds list of MediaWiki configuration settings to be unset in tearDown().
98 * See also setMwGlobals().
99 * @var array
100 */
101 private $mwGlobalsToUnset = [];
102
103 /**
104 * Holds original loggers which have been replaced by setLogger()
105 * @var LoggerInterface[]
106 */
107 private $loggers = [];
108
109 /**
110 * The CLI arguments passed through from phpunit.php
111 * @var array
112 */
113 private $cliArgs = [];
114
115 /**
116 * Table name prefixes. Oracle likes it shorter.
117 */
118 const DB_PREFIX = 'unittest_';
119 const ORA_DB_PREFIX = 'ut_';
120
121 /**
122 * @var array
123 * @since 1.18
124 */
125 protected $supportedDBs = [
126 'mysql',
127 'sqlite',
128 'postgres',
129 'oracle'
130 ];
131
132 public function __construct( $name = null, array $data = [], $dataName = '' ) {
133 parent::__construct( $name, $data, $dataName );
134
135 $this->backupGlobals = false;
136 $this->backupStaticAttributes = false;
137 }
138
139 public function __destruct() {
140 // Complain if self::setUp() was called, but not self::tearDown()
141 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
142 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
143 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
144 }
145 }
146
147 public static function setUpBeforeClass() {
148 parent::setUpBeforeClass();
149
150 // Get the original service locator
151 if ( !self::$originalServices ) {
152 self::$originalServices = MediaWikiServices::getInstance();
153 }
154 }
155
156 /**
157 * Convenience method for getting an immutable test user
158 *
159 * @since 1.28
160 *
161 * @param string[] $groups Groups the test user should be in.
162 * @return TestUser
163 */
164 public static function getTestUser( $groups = [] ) {
165 return TestUserRegistry::getImmutableTestUser( $groups );
166 }
167
168 /**
169 * Convenience method for getting a mutable test user
170 *
171 * @since 1.28
172 *
173 * @param string[] $groups Groups the test user should be added in.
174 * @return TestUser
175 */
176 public static function getMutableTestUser( $groups = [] ) {
177 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
178 }
179
180 /**
181 * Convenience method for getting an immutable admin test user
182 *
183 * @since 1.28
184 *
185 * @param string[] $groups Groups the test user should be added to.
186 * @return TestUser
187 */
188 public static function getTestSysop() {
189 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
190 }
191
192 /**
193 * Returns a WikiPage representing an existing page.
194 *
195 * @since 1.32
196 *
197 * @param Title|string|null $title
198 * @return WikiPage
199 * @throws MWException If this test cases's needsDB() method doesn't return true.
200 * Test cases can use "@group Database" to enable database test support,
201 * or list the tables under testing in $this->tablesUsed, or override the
202 * needsDB() method.
203 */
204 protected function getExistingTestPage( $title = null ) {
205 if ( !$this->needsDB() ) {
206 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
207 ' method should return true. Use @group Database or $this->tablesUsed.' );
208 }
209
210 $title = ( $title === null ) ? 'UTPage' : $title;
211 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
212 $page = WikiPage::factory( $title );
213
214 if ( !$page->exists() ) {
215 $user = self::getTestSysop()->getUser();
216 $page->doEditContent(
217 new WikitextContent( 'UTContent' ),
218 'UTPageSummary',
219 EDIT_NEW | EDIT_SUPPRESS_RC,
220 false,
221 $user
222 );
223 }
224
225 return $page;
226 }
227
228 /**
229 * Returns a WikiPage representing a non-existing page.
230 *
231 * @since 1.32
232 *
233 * @param Title|string|null $title
234 * @return WikiPage
235 * @throws MWException If this test cases's needsDB() method doesn't return true.
236 * Test cases can use "@group Database" to enable database test support,
237 * or list the tables under testing in $this->tablesUsed, or override the
238 * needsDB() method.
239 */
240 protected function getNonexistingTestPage( $title = null ) {
241 if ( !$this->needsDB() ) {
242 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
243 ' method should return true. Use @group Database or $this->tablesUsed.' );
244 }
245
246 $title = ( $title === null ) ? 'UTPage-' . rand( 0, 100000 ) : $title;
247 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
248 $page = WikiPage::factory( $title );
249
250 if ( $page->exists() ) {
251 $page->doDeleteArticle( 'Testing' );
252 }
253
254 return $page;
255 }
256
257 /**
258 * @deprecated since 1.32
259 */
260 public static function prepareServices( Config $bootstrapConfig ) {
261 }
262
263 /**
264 * Create a config suitable for testing, based on a base config, default overrides,
265 * and custom overrides.
266 *
267 * @param Config|null $baseConfig
268 * @param Config|null $customOverrides
269 *
270 * @return Config
271 */
272 private static function makeTestConfig(
273 Config $baseConfig = null,
274 Config $customOverrides = null
275 ) {
276 $defaultOverrides = new HashConfig();
277
278 if ( !$baseConfig ) {
279 $baseConfig = self::$originalServices->getBootstrapConfig();
280 }
281
282 /* Some functions require some kind of caching, and will end up using the db,
283 * which we can't allow, as that would open a new connection for mysql.
284 * Replace with a HashBag. They would not be going to persist anyway.
285 */
286 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
287 $objectCaches = [
288 CACHE_DB => $hashCache,
289 CACHE_ACCEL => $hashCache,
290 CACHE_MEMCACHED => $hashCache,
291 'apc' => $hashCache,
292 'apcu' => $hashCache,
293 'wincache' => $hashCache,
294 ] + $baseConfig->get( 'ObjectCaches' );
295
296 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
297 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
298 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory::class ] ] );
299
300 // Use a fast hash algorithm to hash passwords.
301 $defaultOverrides->set( 'PasswordDefault', 'A' );
302
303 $testConfig = $customOverrides
304 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
305 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
306
307 return $testConfig;
308 }
309
310 /**
311 * @param ConfigFactory $oldFactory
312 * @param Config[] $configurations
313 *
314 * @return Closure
315 */
316 private static function makeTestConfigFactoryInstantiator(
317 ConfigFactory $oldFactory,
318 array $configurations
319 ) {
320 return function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
321 $factory = new ConfigFactory();
322
323 // clone configurations from $oldFactory that are not overwritten by $configurations
324 $namesToClone = array_diff(
325 $oldFactory->getConfigNames(),
326 array_keys( $configurations )
327 );
328
329 foreach ( $namesToClone as $name ) {
330 $factory->register( $name, $oldFactory->makeConfig( $name ) );
331 }
332
333 foreach ( $configurations as $name => $config ) {
334 $factory->register( $name, $config );
335 }
336
337 return $factory;
338 };
339 }
340
341 /**
342 * Resets some non-service singleton instances and other static caches. It's not necessary to
343 * reset services here.
344 */
345 public static function resetNonServiceCaches() {
346 global $wgRequest, $wgJobClasses;
347
348 foreach ( $wgJobClasses as $type => $class ) {
349 JobQueueGroup::singleton()->get( $type )->delete();
350 }
351 JobQueueGroup::destroySingletons();
352
353 ObjectCache::clear();
354 FileBackendGroup::destroySingleton();
355 DeferredUpdates::clearPendingUpdates();
356
357 // TODO: move global state into MediaWikiServices
358 RequestContext::resetMain();
359 if ( session_id() !== '' ) {
360 session_write_close();
361 session_id( '' );
362 }
363
364 $wgRequest = new FauxRequest();
365 MediaWiki\Session\SessionManager::resetCache();
366 }
367
368 public function run( PHPUnit_Framework_TestResult $result = null ) {
369 if ( $result instanceof MediaWikiTestResult ) {
370 $this->cliArgs = $result->getMediaWikiCliArgs();
371 }
372 $this->overrideMwServices();
373
374 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
375 throw new Exception(
376 get_class( $this ) . ' apparently needsDB but is not in the Database group'
377 );
378 }
379
380 $needsResetDB = false;
381 if ( !self::$dbSetup || $this->needsDB() ) {
382 // set up a DB connection for this test to use
383
384 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
385 self::$reuseDB = $this->getCliArg( 'reuse-db' );
386
387 $this->db = wfGetDB( DB_MASTER );
388
389 $this->checkDbIsSupported();
390
391 if ( !self::$dbSetup ) {
392 $this->setupAllTestDBs();
393 $this->addCoreDBData();
394 }
395
396 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
397 // is available in subclass's setUpBeforeClass() and setUp() methods.
398 // This would also remove the need for the HACK that is oncePerClass().
399 if ( $this->oncePerClass() ) {
400 $this->setUpSchema( $this->db );
401 $this->resetDB( $this->db, $this->tablesUsed );
402 $this->addDBDataOnce();
403 }
404
405 $this->addDBData();
406 $needsResetDB = true;
407 }
408
409 parent::run( $result );
410
411 if ( $needsResetDB ) {
412 $this->resetDB( $this->db, $this->tablesUsed );
413 }
414
415 self::restoreMwServices();
416 $this->localServices = null;
417 }
418
419 /**
420 * @return bool
421 */
422 private function oncePerClass() {
423 // Remember current test class in the database connection,
424 // so we know when we need to run addData.
425
426 $class = static::class;
427
428 $first = !isset( $this->db->_hasDataForTestClass )
429 || $this->db->_hasDataForTestClass !== $class;
430
431 $this->db->_hasDataForTestClass = $class;
432 return $first;
433 }
434
435 /**
436 * @since 1.21
437 *
438 * @return bool
439 */
440 public function usesTemporaryTables() {
441 return self::$useTemporaryTables;
442 }
443
444 /**
445 * Obtains a new temporary file name
446 *
447 * The obtained filename is enlisted to be removed upon tearDown
448 *
449 * @since 1.20
450 *
451 * @return string Absolute name of the temporary file
452 */
453 protected function getNewTempFile() {
454 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
455 $this->tmpFiles[] = $fileName;
456
457 return $fileName;
458 }
459
460 /**
461 * obtains a new temporary directory
462 *
463 * The obtained directory is enlisted to be removed (recursively with all its contained
464 * files) upon tearDown.
465 *
466 * @since 1.20
467 *
468 * @return string Absolute name of the temporary directory
469 */
470 protected function getNewTempDirectory() {
471 // Starting of with a temporary /file/.
472 $fileName = $this->getNewTempFile();
473
474 // Converting the temporary /file/ to a /directory/
475 // The following is not atomic, but at least we now have a single place,
476 // where temporary directory creation is bundled and can be improved
477 unlink( $fileName );
478 $this->assertTrue( wfMkdirParents( $fileName ) );
479
480 return $fileName;
481 }
482
483 protected function setUp() {
484 parent::setUp();
485 $this->called['setUp'] = true;
486
487 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
488
489 // Cleaning up temporary files
490 foreach ( $this->tmpFiles as $fileName ) {
491 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
492 unlink( $fileName );
493 } elseif ( is_dir( $fileName ) ) {
494 wfRecursiveRemoveDir( $fileName );
495 }
496 }
497
498 if ( $this->needsDB() && $this->db ) {
499 // Clean up open transactions
500 while ( $this->db->trxLevel() > 0 ) {
501 $this->db->rollback( __METHOD__, 'flush' );
502 }
503 // Check for unsafe queries
504 if ( $this->db->getType() === 'mysql' ) {
505 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__ );
506 }
507 }
508
509 // Reset all caches between tests.
510 self::resetNonServiceCaches();
511
512 // XXX: reset maintenance triggers
513 // Hook into period lag checks which often happen in long-running scripts
514 $lbFactory = $this->localServices->getDBLoadBalancerFactory();
515 Maintenance::setLBFactoryTriggers( $lbFactory, $this->localServices->getMainConfig() );
516
517 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
518 }
519
520 protected function addTmpFiles( $files ) {
521 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
522 }
523
524 protected function tearDown() {
525 global $wgRequest, $wgSQLMode;
526
527 $status = ob_get_status();
528 if ( isset( $status['name'] ) &&
529 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
530 ) {
531 ob_end_flush();
532 }
533
534 $this->called['tearDown'] = true;
535 // Cleaning up temporary files
536 foreach ( $this->tmpFiles as $fileName ) {
537 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
538 unlink( $fileName );
539 } elseif ( is_dir( $fileName ) ) {
540 wfRecursiveRemoveDir( $fileName );
541 }
542 }
543
544 if ( $this->needsDB() && $this->db ) {
545 // Clean up open transactions
546 while ( $this->db->trxLevel() > 0 ) {
547 $this->db->rollback( __METHOD__, 'flush' );
548 }
549 if ( $this->db->getType() === 'mysql' ) {
550 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ),
551 __METHOD__ );
552 }
553 }
554
555 // Re-enable any disabled deprecation warnings
556 MWDebug::clearLog();
557 // Restore mw globals
558 foreach ( $this->mwGlobals as $key => $value ) {
559 $GLOBALS[$key] = $value;
560 }
561 foreach ( $this->mwGlobalsToUnset as $value ) {
562 unset( $GLOBALS[$value] );
563 }
564 if (
565 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals ) ||
566 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset )
567 ) {
568 $this->resetNamespaces();
569 }
570 $this->mwGlobals = [];
571 $this->mwGlobalsToUnset = [];
572 $this->restoreLoggers();
573
574 // TODO: move global state into MediaWikiServices
575 RequestContext::resetMain();
576 if ( session_id() !== '' ) {
577 session_write_close();
578 session_id( '' );
579 }
580 $wgRequest = new FauxRequest();
581 MediaWiki\Session\SessionManager::resetCache();
582 MediaWiki\Auth\AuthManager::resetCache();
583
584 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
585
586 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
587 ini_set( 'error_reporting', $this->phpErrorLevel );
588
589 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
590 $newHex = strtoupper( dechex( $phpErrorLevel ) );
591 $message = "PHP error_reporting setting was left dirty: "
592 . "was 0x$oldHex before test, 0x$newHex after test!";
593
594 $this->fail( $message );
595 }
596
597 parent::tearDown();
598 }
599
600 /**
601 * Make sure MediaWikiTestCase extending classes have called their
602 * parent setUp method
603 *
604 * With strict coverage activated in PHP_CodeCoverage, this test would be
605 * marked as risky without the following annotation (T152923).
606 * @coversNothing
607 */
608 final public function testMediaWikiTestCaseParentSetupCalled() {
609 $this->assertArrayHasKey( 'setUp', $this->called,
610 static::class . '::setUp() must call parent::setUp()'
611 );
612 }
613
614 /**
615 * Sets a service, maintaining a stashed version of the previous service to be
616 * restored in tearDown
617 *
618 * @since 1.27
619 *
620 * @param string $name
621 * @param object $object
622 */
623 protected function setService( $name, $object ) {
624 if ( !$this->localServices ) {
625 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
626 }
627
628 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
629 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
630 . 'instance has been replaced by test code.' );
631 }
632
633 $this->localServices->disableService( $name );
634 $this->localServices->redefineService(
635 $name,
636 function () use ( $object ) {
637 return $object;
638 }
639 );
640
641 if ( $name === 'ContentLanguage' ) {
642 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
643 }
644 }
645
646 /**
647 * Sets a global, maintaining a stashed version of the previous global to be
648 * restored in tearDown
649 *
650 * The key is added to the array of globals that will be reset afterwards
651 * in the tearDown().
652 *
653 * @par Example
654 * @code
655 * protected function setUp() {
656 * $this->setMwGlobals( 'wgRestrictStuff', true );
657 * }
658 *
659 * function testFoo() {}
660 *
661 * function testBar() {}
662 * $this->assertTrue( self::getX()->doStuff() );
663 *
664 * $this->setMwGlobals( 'wgRestrictStuff', false );
665 * $this->assertTrue( self::getX()->doStuff() );
666 * }
667 *
668 * function testQuux() {}
669 * @endcode
670 *
671 * @param array|string $pairs Key to the global variable, or an array
672 * of key/value pairs.
673 * @param mixed|null $value Value to set the global to (ignored
674 * if an array is given as first argument).
675 *
676 * @note To allow changes to global variables to take effect on global service instances,
677 * call overrideMwServices().
678 *
679 * @since 1.21
680 */
681 protected function setMwGlobals( $pairs, $value = null ) {
682 if ( is_string( $pairs ) ) {
683 $pairs = [ $pairs => $value ];
684 }
685
686 if ( isset( $pairs['wgContLang'] ) ) {
687 throw new MWException(
688 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
689 );
690 }
691
692 $this->doSetMwGlobals( $pairs, $value );
693 }
694
695 /**
696 * An internal method that allows setService() to set globals that tests are not supposed to
697 * touch.
698 */
699 private function doSetMwGlobals( $pairs, $value = null ) {
700 $this->stashMwGlobals( array_keys( $pairs ) );
701
702 foreach ( $pairs as $key => $value ) {
703 $GLOBALS[$key] = $value;
704 }
705
706 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
707 $this->resetNamespaces();
708 }
709 }
710
711 /**
712 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
713 * Otherwise old namespace data will lurk and cause bugs.
714 */
715 private function resetNamespaces() {
716 if ( !$this->localServices ) {
717 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
718 }
719
720 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
721 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
722 . 'instance has been replaced by test code.' );
723 }
724
725 MWNamespace::clearCaches();
726 Language::clearCaches();
727
728 // We can't have the TitleFormatter holding on to an old Language object either
729 // @todo We shouldn't need to reset all the aliases here.
730 $this->localServices->resetServiceForTesting( 'TitleFormatter' );
731 $this->localServices->resetServiceForTesting( 'TitleParser' );
732 $this->localServices->resetServiceForTesting( '_MediaWikiTitleCodec' );
733 }
734
735 /**
736 * Check if we can back up a value by performing a shallow copy.
737 * Values which fail this test are copied recursively.
738 *
739 * @param mixed $value
740 * @return bool True if a shallow copy will do; false if a deep copy
741 * is required.
742 */
743 private static function canShallowCopy( $value ) {
744 if ( is_scalar( $value ) || $value === null ) {
745 return true;
746 }
747 if ( is_array( $value ) ) {
748 foreach ( $value as $subValue ) {
749 if ( !is_scalar( $subValue ) && $subValue !== null ) {
750 return false;
751 }
752 }
753 return true;
754 }
755 return false;
756 }
757
758 /**
759 * Stashes the global, will be restored in tearDown()
760 *
761 * Individual test functions may override globals through the setMwGlobals() function
762 * or directly. When directly overriding globals their keys should first be passed to this
763 * method in setUp to avoid breaking global state for other tests
764 *
765 * That way all other tests are executed with the same settings (instead of using the
766 * unreliable local settings for most tests and fix it only for some tests).
767 *
768 * @param array|string $globalKeys Key to the global variable, or an array of keys.
769 *
770 * @note To allow changes to global variables to take effect on global service instances,
771 * call overrideMwServices().
772 *
773 * @since 1.23
774 */
775 protected function stashMwGlobals( $globalKeys ) {
776 if ( is_string( $globalKeys ) ) {
777 $globalKeys = [ $globalKeys ];
778 }
779
780 foreach ( $globalKeys as $globalKey ) {
781 // NOTE: make sure we only save the global once or a second call to
782 // setMwGlobals() on the same global would override the original
783 // value.
784 if (
785 !array_key_exists( $globalKey, $this->mwGlobals ) &&
786 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
787 ) {
788 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
789 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
790 continue;
791 }
792 // NOTE: we serialize then unserialize the value in case it is an object
793 // this stops any objects being passed by reference. We could use clone
794 // and if is_object but this does account for objects within objects!
795 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
796 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
797 } elseif (
798 // Many MediaWiki types are safe to clone. These are the
799 // ones that are most commonly stashed.
800 $GLOBALS[$globalKey] instanceof Language ||
801 $GLOBALS[$globalKey] instanceof User ||
802 $GLOBALS[$globalKey] instanceof FauxRequest
803 ) {
804 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
805 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
806 // Serializing Closure only gives a warning on HHVM while
807 // it throws an Exception on Zend.
808 // Workaround for https://github.com/facebook/hhvm/issues/6206
809 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
810 } else {
811 try {
812 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
813 } catch ( Exception $e ) {
814 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
815 }
816 }
817 }
818 }
819 }
820
821 /**
822 * @param mixed $var
823 * @param int $maxDepth
824 *
825 * @return bool
826 */
827 private function containsClosure( $var, $maxDepth = 15 ) {
828 if ( $var instanceof Closure ) {
829 return true;
830 }
831 if ( !is_array( $var ) || $maxDepth === 0 ) {
832 return false;
833 }
834
835 foreach ( $var as $value ) {
836 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
837 return true;
838 }
839 }
840 return false;
841 }
842
843 /**
844 * Merges the given values into a MW global array variable.
845 * Useful for setting some entries in a configuration array, instead of
846 * setting the entire array.
847 *
848 * @param string $name The name of the global, as in wgFooBar
849 * @param array $values The array containing the entries to set in that global
850 *
851 * @throws MWException If the designated global is not an array.
852 *
853 * @note To allow changes to global variables to take effect on global service instances,
854 * call overrideMwServices().
855 *
856 * @since 1.21
857 */
858 protected function mergeMwGlobalArrayValue( $name, $values ) {
859 if ( !isset( $GLOBALS[$name] ) ) {
860 $merged = $values;
861 } else {
862 if ( !is_array( $GLOBALS[$name] ) ) {
863 throw new MWException( "MW global $name is not an array." );
864 }
865
866 // NOTE: do not use array_merge, it screws up for numeric keys.
867 $merged = $GLOBALS[$name];
868 foreach ( $values as $k => $v ) {
869 $merged[$k] = $v;
870 }
871 }
872
873 $this->setMwGlobals( $name, $merged );
874 }
875
876 /**
877 * Stashes the global instance of MediaWikiServices, and installs a new one,
878 * allowing test cases to override settings and services.
879 * The previous instance of MediaWikiServices will be restored on tearDown.
880 *
881 * @since 1.27
882 *
883 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
884 * instance.
885 * @param callable[] $services An associative array of services to re-define. Keys are service
886 * names, values are callables.
887 *
888 * @return MediaWikiServices
889 * @throws MWException
890 */
891 protected function overrideMwServices(
892 Config $configOverrides = null, array $services = []
893 ) {
894 $newInstance = self::installMockMwServices( $configOverrides );
895
896 if ( $this->localServices ) {
897 $this->localServices->destroy();
898 }
899
900 $this->localServices = $newInstance;
901
902 foreach ( $services as $name => $callback ) {
903 $newInstance->redefineService( $name, $callback );
904 }
905
906 return $newInstance;
907 }
908
909 /**
910 * Creates a new "mock" MediaWikiServices instance, and installs it.
911 * This effectively resets all cached states in services, with the exception of
912 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
913 * the original MediaWikiServices.
914 *
915 * @note The new original MediaWikiServices instance can later be restored by calling
916 * restoreMwServices(). That original is determined by the first call to this method, or
917 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
918 * and, when appropriate, destroying any other MediaWikiServices instances that may get
919 * replaced when calling this method.
920 *
921 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
922 * instance.
923 *
924 * @return MediaWikiServices the new mock service locator.
925 */
926 public static function installMockMwServices( Config $configOverrides = null ) {
927 // Make sure we have the original service locator
928 if ( !self::$originalServices ) {
929 self::$originalServices = MediaWikiServices::getInstance();
930 }
931
932 if ( !$configOverrides ) {
933 $configOverrides = new HashConfig();
934 }
935
936 $oldConfigFactory = self::$originalServices->getConfigFactory();
937 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
938
939 $testConfig = self::makeTestConfig( null, $configOverrides );
940 $newServices = new MediaWikiServices( $testConfig );
941
942 // Load the default wiring from the specified files.
943 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
944 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
945 $newServices->loadWiringFiles( $wiringFiles );
946
947 // Provide a traditional hook point to allow extensions to configure services.
948 Hooks::run( 'MediaWikiServices', [ $newServices ] );
949
950 // Use bootstrap config for all configuration.
951 // This allows config overrides via global variables to take effect.
952 $bootstrapConfig = $newServices->getBootstrapConfig();
953 $newServices->resetServiceForTesting( 'ConfigFactory' );
954 $newServices->redefineService(
955 'ConfigFactory',
956 self::makeTestConfigFactoryInstantiator(
957 $oldConfigFactory,
958 [ 'main' => $bootstrapConfig ]
959 )
960 );
961 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
962 $newServices->redefineService(
963 'DBLoadBalancerFactory',
964 function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
965 return $oldLoadBalancerFactory;
966 }
967 );
968
969 MediaWikiServices::forceGlobalInstance( $newServices );
970 return $newServices;
971 }
972
973 /**
974 * Restores the original, non-mock MediaWikiServices instance.
975 * The previously active MediaWikiServices instance is destroyed,
976 * if it is different from the original that is to be restored.
977 *
978 * @note this if for internal use by test framework code. It should never be
979 * called from inside a test case, a data provider, or a setUp or tearDown method.
980 *
981 * @return bool true if the original service locator was restored,
982 * false if there was nothing too do.
983 */
984 public static function restoreMwServices() {
985 if ( !self::$originalServices ) {
986 return false;
987 }
988
989 $currentServices = MediaWikiServices::getInstance();
990
991 if ( self::$originalServices === $currentServices ) {
992 return false;
993 }
994
995 MediaWikiServices::forceGlobalInstance( self::$originalServices );
996 $currentServices->destroy();
997
998 return true;
999 }
1000
1001 /**
1002 * @since 1.27
1003 * @param string|Language $lang
1004 */
1005 public function setUserLang( $lang ) {
1006 RequestContext::getMain()->setLanguage( $lang );
1007 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
1008 }
1009
1010 /**
1011 * @since 1.27
1012 * @param string|Language $lang
1013 */
1014 public function setContentLang( $lang ) {
1015 if ( $lang instanceof Language ) {
1016 $langCode = $lang->getCode();
1017 $langObj = $lang;
1018 } else {
1019 $langCode = $lang;
1020 $langObj = Language::factory( $langCode );
1021 }
1022 $this->setMwGlobals( 'wgLanguageCode', $langCode );
1023 $this->setService( 'ContentLanguage', $langObj );
1024 }
1025
1026 /**
1027 * Alters $wgGroupPermissions for the duration of the test. Can be called
1028 * with an array, like
1029 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1030 * or three values to set a single permission, like
1031 * $this->setGroupPermissions( '*', 'read', false );
1032 *
1033 * @since 1.31
1034 * @param array|string $newPerms Either an array of permissions to change,
1035 * in which case the next two parameters are ignored; or a single string
1036 * identifying a group, to use with the next two parameters.
1037 * @param string|null $newKey
1038 * @param mixed|null $newValue
1039 */
1040 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1041 global $wgGroupPermissions;
1042
1043 $this->stashMwGlobals( 'wgGroupPermissions' );
1044
1045 if ( is_string( $newPerms ) ) {
1046 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1047 }
1048
1049 foreach ( $newPerms as $group => $permissions ) {
1050 foreach ( $permissions as $key => $value ) {
1051 $wgGroupPermissions[$group][$key] = $value;
1052 }
1053 }
1054 }
1055
1056 /**
1057 * Sets the logger for a specified channel, for the duration of the test.
1058 * @since 1.27
1059 * @param string $channel
1060 * @param LoggerInterface $logger
1061 */
1062 protected function setLogger( $channel, LoggerInterface $logger ) {
1063 // TODO: Once loggers are managed by MediaWikiServices, use
1064 // overrideMwServices() to set loggers.
1065
1066 $provider = LoggerFactory::getProvider();
1067 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1068 $singletons = $wrappedProvider->singletons;
1069 if ( $provider instanceof MonologSpi ) {
1070 if ( !isset( $this->loggers[$channel] ) ) {
1071 $this->loggers[$channel] = $singletons['loggers'][$channel] ?? null;
1072 }
1073 $singletons['loggers'][$channel] = $logger;
1074 } elseif ( $provider instanceof LegacySpi ) {
1075 if ( !isset( $this->loggers[$channel] ) ) {
1076 $this->loggers[$channel] = $singletons[$channel] ?? null;
1077 }
1078 $singletons[$channel] = $logger;
1079 } else {
1080 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
1081 . ' is not implemented' );
1082 }
1083 $wrappedProvider->singletons = $singletons;
1084 }
1085
1086 /**
1087 * Restores loggers replaced by setLogger().
1088 * @since 1.27
1089 */
1090 private function restoreLoggers() {
1091 $provider = LoggerFactory::getProvider();
1092 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1093 $singletons = $wrappedProvider->singletons;
1094 foreach ( $this->loggers as $channel => $logger ) {
1095 if ( $provider instanceof MonologSpi ) {
1096 if ( $logger === null ) {
1097 unset( $singletons['loggers'][$channel] );
1098 } else {
1099 $singletons['loggers'][$channel] = $logger;
1100 }
1101 } elseif ( $provider instanceof LegacySpi ) {
1102 if ( $logger === null ) {
1103 unset( $singletons[$channel] );
1104 } else {
1105 $singletons[$channel] = $logger;
1106 }
1107 }
1108 }
1109 $wrappedProvider->singletons = $singletons;
1110 $this->loggers = [];
1111 }
1112
1113 /**
1114 * @return string
1115 * @since 1.18
1116 */
1117 public function dbPrefix() {
1118 return self::getTestPrefixFor( $this->db );
1119 }
1120
1121 /**
1122 * @param IDatabase $db
1123 * @return string
1124 * @since 1.32
1125 */
1126 public static function getTestPrefixFor( IDatabase $db ) {
1127 return $db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
1128 }
1129
1130 /**
1131 * @return bool
1132 * @since 1.18
1133 */
1134 public function needsDB() {
1135 // If the test says it uses database tables, it needs the database
1136 return $this->tablesUsed || $this->isTestInDatabaseGroup();
1137 }
1138
1139 /**
1140 * @return bool
1141 * @since 1.32
1142 */
1143 protected function isTestInDatabaseGroup() {
1144 // If the test class says it belongs to the Database group, it needs the database.
1145 // NOTE: This ONLY checks for the group in the class level doc comment.
1146 $rc = new ReflectionClass( $this );
1147 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1148 }
1149
1150 /**
1151 * Insert a new page.
1152 *
1153 * Should be called from addDBData().
1154 *
1155 * @since 1.25 ($namespace in 1.28)
1156 * @param string|Title $pageName Page name or title
1157 * @param string $text Page's content
1158 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1159 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1160 * @return array Title object and page id
1161 * @throws MWException If this test cases's needsDB() method doesn't return true.
1162 * Test cases can use "@group Database" to enable database test support,
1163 * or list the tables under testing in $this->tablesUsed, or override the
1164 * needsDB() method.
1165 */
1166 protected function insertPage(
1167 $pageName,
1168 $text = 'Sample page for unit test.',
1169 $namespace = null,
1170 User $user = null
1171 ) {
1172 if ( !$this->needsDB() ) {
1173 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1174 ' method should return true. Use @group Database or $this->tablesUsed.' );
1175 }
1176
1177 if ( is_string( $pageName ) ) {
1178 $title = Title::newFromText( $pageName, $namespace );
1179 } else {
1180 $title = $pageName;
1181 }
1182
1183 if ( !$user ) {
1184 $user = static::getTestSysop()->getUser();
1185 }
1186 $comment = __METHOD__ . ': Sample page for unit test.';
1187
1188 $page = WikiPage::factory( $title );
1189 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
1190
1191 return [
1192 'title' => $title,
1193 'id' => $page->getId(),
1194 ];
1195 }
1196
1197 /**
1198 * Stub. If a test suite needs to add additional data to the database, it should
1199 * implement this method and do so. This method is called once per test suite
1200 * (i.e. once per class).
1201 *
1202 * Note data added by this method may be removed by resetDB() depending on
1203 * the contents of $tablesUsed.
1204 *
1205 * To add additional data between test function runs, override prepareDB().
1206 *
1207 * @see addDBData()
1208 * @see resetDB()
1209 *
1210 * @since 1.27
1211 */
1212 public function addDBDataOnce() {
1213 }
1214
1215 /**
1216 * Stub. Subclasses may override this to prepare the database.
1217 * Called before every test run (test function or data set).
1218 *
1219 * @see addDBDataOnce()
1220 * @see resetDB()
1221 *
1222 * @since 1.18
1223 */
1224 public function addDBData() {
1225 }
1226
1227 /**
1228 * @since 1.32
1229 */
1230 protected function addCoreDBData() {
1231 if ( $this->db->getType() == 'oracle' ) {
1232 # Insert 0 user to prevent FK violations
1233 # Anonymous user
1234 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1235 $this->db->insert( 'user', [
1236 'user_id' => 0,
1237 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
1238 }
1239
1240 # Insert 0 page to prevent FK violations
1241 # Blank page
1242 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1243 $this->db->insert( 'page', [
1244 'page_id' => 0,
1245 'page_namespace' => 0,
1246 'page_title' => ' ',
1247 'page_restrictions' => null,
1248 'page_is_redirect' => 0,
1249 'page_is_new' => 0,
1250 'page_random' => 0,
1251 'page_touched' => $this->db->timestamp(),
1252 'page_latest' => 0,
1253 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1254 }
1255 }
1256
1257 SiteStatsInit::doPlaceholderInit();
1258
1259 User::resetIdByNameCache();
1260
1261 // Make sysop user
1262 $user = static::getTestSysop()->getUser();
1263
1264 // Make 1 page with 1 revision
1265 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1266 if ( $page->getId() == 0 ) {
1267 $page->doEditContent(
1268 new WikitextContent( 'UTContent' ),
1269 'UTPageSummary',
1270 EDIT_NEW | EDIT_SUPPRESS_RC,
1271 false,
1272 $user
1273 );
1274 // an edit always attempt to purge backlink links such as history
1275 // pages. That is unnecessary.
1276 JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->delete();
1277 // WikiPages::doEditUpdates randomly adds RC purges
1278 JobQueueGroup::singleton()->get( 'recentChangesUpdate' )->delete();
1279
1280 // doEditContent() probably started the session via
1281 // User::loadFromSession(). Close it now.
1282 if ( session_id() !== '' ) {
1283 session_write_close();
1284 session_id( '' );
1285 }
1286 }
1287 }
1288
1289 /**
1290 * Restores MediaWiki to using the table set (table prefix) it was using before
1291 * setupTestDB() was called. Useful if we need to perform database operations
1292 * after the test run has finished (such as saving logs or profiling info).
1293 *
1294 * This is called by phpunit/bootstrap.php after the last test.
1295 *
1296 * @since 1.21
1297 */
1298 public static function teardownTestDB() {
1299 global $wgJobClasses;
1300
1301 if ( !self::$dbSetup ) {
1302 return;
1303 }
1304
1305 Hooks::run( 'UnitTestsBeforeDatabaseTeardown' );
1306
1307 foreach ( $wgJobClasses as $type => $class ) {
1308 // Delete any jobs under the clone DB (or old prefix in other stores)
1309 JobQueueGroup::singleton()->get( $type )->delete();
1310 }
1311
1312 CloneDatabase::changePrefix( self::$oldTablePrefix );
1313
1314 self::$oldTablePrefix = false;
1315 self::$dbSetup = false;
1316 }
1317
1318 /**
1319 * Setups a database with cloned tables using the given prefix.
1320 *
1321 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1322 * Otherwise, it will clone the tables and change the prefix.
1323 *
1324 * @param IMaintainableDatabase $db Database to use
1325 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1326 * automatically for $db.
1327 * @return bool True if tables were cloned, false if only the prefix was changed
1328 */
1329 protected static function setupDatabaseWithTestPrefix(
1330 IMaintainableDatabase $db,
1331 $prefix = null
1332 ) {
1333 if ( $prefix === null ) {
1334 $prefix = self::getTestPrefixFor( $db );
1335 }
1336
1337 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1338 $db->tablePrefix( $prefix );
1339 return false;
1340 }
1341
1342 if ( !isset( $db->_originalTablePrefix ) ) {
1343 $oldPrefix = $db->tablePrefix();
1344
1345 if ( $oldPrefix === $prefix ) {
1346 // table already has the correct prefix, but presumably no cloned tables
1347 $oldPrefix = self::$oldTablePrefix;
1348 }
1349
1350 $db->tablePrefix( $oldPrefix );
1351 $tablesCloned = self::listTables( $db );
1352 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1353 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1354
1355 $dbClone->cloneTableStructure();
1356
1357 $db->tablePrefix( $prefix );
1358 $db->_originalTablePrefix = $oldPrefix;
1359 }
1360
1361 return true;
1362 }
1363
1364 /**
1365 * Set up all test DBs
1366 */
1367 public function setupAllTestDBs() {
1368 global $wgDBprefix;
1369
1370 self::$oldTablePrefix = $wgDBprefix;
1371
1372 $testPrefix = $this->dbPrefix();
1373
1374 // switch to a temporary clone of the database
1375 self::setupTestDB( $this->db, $testPrefix );
1376
1377 if ( self::isUsingExternalStoreDB() ) {
1378 self::setupExternalStoreTestDBs( $testPrefix );
1379 }
1380
1381 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1382 // *any* database connections to operate on live data.
1383 CloneDatabase::changePrefix( $testPrefix );
1384 }
1385
1386 /**
1387 * Creates an empty skeleton of the wiki database by cloning its structure
1388 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1389 * use the new set of tables (aka schema) instead of the original set.
1390 *
1391 * This is used to generate a dummy table set, typically consisting of temporary
1392 * tables, that will be used by tests instead of the original wiki database tables.
1393 *
1394 * @since 1.21
1395 *
1396 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1397 * by teardownTestDB() to return the wiki to using the original table set.
1398 *
1399 * @note this method only works when first called. Subsequent calls have no effect,
1400 * even if using different parameters.
1401 *
1402 * @param Database $db The database connection
1403 * @param string $prefix The prefix to use for the new table set (aka schema).
1404 *
1405 * @throws MWException If the database table prefix is already $prefix
1406 */
1407 public static function setupTestDB( Database $db, $prefix ) {
1408 if ( self::$dbSetup ) {
1409 return;
1410 }
1411
1412 if ( $db->tablePrefix() === $prefix ) {
1413 throw new MWException(
1414 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1415 }
1416
1417 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1418 // and Database no longer use global state.
1419
1420 self::$dbSetup = true;
1421
1422 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1423 return;
1424 }
1425
1426 // Assuming this isn't needed for External Store database, and not sure if the procedure
1427 // would be available there.
1428 if ( $db->getType() == 'oracle' ) {
1429 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__ );
1430 }
1431
1432 Hooks::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1433 }
1434
1435 /**
1436 * Clones the External Store database(s) for testing
1437 *
1438 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1439 * if not given.
1440 */
1441 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1442 $connections = self::getExternalStoreDatabaseConnections();
1443 foreach ( $connections as $dbw ) {
1444 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1445 }
1446 }
1447
1448 /**
1449 * Gets master database connections for all of the ExternalStoreDB
1450 * stores configured in $wgDefaultExternalStore.
1451 *
1452 * @return Database[] Array of Database master connections
1453 */
1454 protected static function getExternalStoreDatabaseConnections() {
1455 global $wgDefaultExternalStore;
1456
1457 /** @var ExternalStoreDB $externalStoreDB */
1458 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1459 $defaultArray = (array)$wgDefaultExternalStore;
1460 $dbws = [];
1461 foreach ( $defaultArray as $url ) {
1462 if ( strpos( $url, 'DB://' ) === 0 ) {
1463 list( $proto, $cluster ) = explode( '://', $url, 2 );
1464 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1465 // requires Database instead of plain DBConnRef/IDatabase
1466 $dbws[] = $externalStoreDB->getMaster( $cluster );
1467 }
1468 }
1469
1470 return $dbws;
1471 }
1472
1473 /**
1474 * Check whether ExternalStoreDB is being used
1475 *
1476 * @return bool True if it's being used
1477 */
1478 protected static function isUsingExternalStoreDB() {
1479 global $wgDefaultExternalStore;
1480 if ( !$wgDefaultExternalStore ) {
1481 return false;
1482 }
1483
1484 $defaultArray = (array)$wgDefaultExternalStore;
1485 foreach ( $defaultArray as $url ) {
1486 if ( strpos( $url, 'DB://' ) === 0 ) {
1487 return true;
1488 }
1489 }
1490
1491 return false;
1492 }
1493
1494 /**
1495 * @throws LogicException if the given database connection is not a set up to use
1496 * mock tables.
1497 *
1498 * @since 1.31 this is no longer private.
1499 */
1500 protected function ensureMockDatabaseConnection( IDatabase $db ) {
1501 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1502 throw new LogicException(
1503 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1504 );
1505 }
1506 }
1507
1508 private static $schemaOverrideDefaults = [
1509 'scripts' => [],
1510 'create' => [],
1511 'drop' => [],
1512 'alter' => [],
1513 ];
1514
1515 /**
1516 * Stub. If a test suite needs to test against a specific database schema, it should
1517 * override this method and return the appropriate information from it.
1518 *
1519 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1520 * May be used to check the current state of the schema, to determine what
1521 * overrides are needed.
1522 *
1523 * @return array An associative array with the following fields:
1524 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1525 * - 'create': A list of tables created (may or may not exist in the original schema).
1526 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1527 * - 'alter': A list of tables altered (expected to be present in the original schema).
1528 */
1529 protected function getSchemaOverrides( IMaintainableDatabase $db ) {
1530 return [];
1531 }
1532
1533 /**
1534 * Undoes the specified schema overrides..
1535 * Called once per test class, just before addDataOnce().
1536 *
1537 * @param IMaintainableDatabase $db
1538 * @param array $oldOverrides
1539 */
1540 private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOverrides ) {
1541 $this->ensureMockDatabaseConnection( $db );
1542
1543 $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
1544 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1545
1546 // Drop tables that need to be restored or removed.
1547 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1548
1549 // Restore tables that have been dropped or created or altered,
1550 // if they exist in the original schema.
1551 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1552 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1553
1554 if ( $tablesToDrop ) {
1555 $this->dropMockTables( $db, $tablesToDrop );
1556 }
1557
1558 if ( $tablesToRestore ) {
1559 $this->recloneMockTables( $db, $tablesToRestore );
1560 }
1561 }
1562
1563 /**
1564 * Applies the schema overrides returned by getSchemaOverrides(),
1565 * after undoing any previously applied schema overrides.
1566 * Called once per test class, just before addDataOnce().
1567 */
1568 private function setUpSchema( IMaintainableDatabase $db ) {
1569 // Undo any active overrides.
1570 $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDefaults;
1571
1572 if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) {
1573 $this->undoSchemaOverrides( $db, $oldOverrides );
1574 }
1575
1576 // Determine new overrides.
1577 $overrides = $this->getSchemaOverrides( $db ) + self::$schemaOverrideDefaults;
1578
1579 $extraKeys = array_diff(
1580 array_keys( $overrides ),
1581 array_keys( self::$schemaOverrideDefaults )
1582 );
1583
1584 if ( $extraKeys ) {
1585 throw new InvalidArgumentException(
1586 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1587 );
1588 }
1589
1590 if ( !$overrides['scripts'] ) {
1591 // no scripts to run
1592 return;
1593 }
1594
1595 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1596 throw new InvalidArgumentException(
1597 'Schema override scripts given, but no tables are declared to be '
1598 . 'created, dropped or altered.'
1599 );
1600 }
1601
1602 $this->ensureMockDatabaseConnection( $db );
1603
1604 // Drop the tables that will be created by the schema scripts.
1605 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1606 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1607
1608 if ( $tablesToDrop ) {
1609 $this->dropMockTables( $db, $tablesToDrop );
1610 }
1611
1612 // Run schema override scripts.
1613 foreach ( $overrides['scripts'] as $script ) {
1614 $db->sourceFile(
1615 $script,
1616 null,
1617 null,
1618 __METHOD__,
1619 function ( $cmd ) {
1620 return $this->mungeSchemaUpdateQuery( $cmd );
1621 }
1622 );
1623 }
1624
1625 $db->_schemaOverrides = $overrides;
1626 }
1627
1628 private function mungeSchemaUpdateQuery( $cmd ) {
1629 return self::$useTemporaryTables
1630 ? preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1631 : $cmd;
1632 }
1633
1634 /**
1635 * Drops the given mock tables.
1636 *
1637 * @param IMaintainableDatabase $db
1638 * @param array $tables
1639 */
1640 private function dropMockTables( IMaintainableDatabase $db, array $tables ) {
1641 $this->ensureMockDatabaseConnection( $db );
1642
1643 foreach ( $tables as $tbl ) {
1644 $tbl = $db->tableName( $tbl );
1645 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
1646 }
1647 }
1648
1649 /**
1650 * Lists all tables in the live database schema.
1651 *
1652 * @param IMaintainableDatabase $db
1653 * @param string $prefix Either 'prefixed' or 'unprefixed'
1654 * @return array
1655 */
1656 private function listOriginalTables( IMaintainableDatabase $db, $prefix = 'prefixed' ) {
1657 if ( !isset( $db->_originalTablePrefix ) ) {
1658 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1659 }
1660
1661 $originalTables = $db->listTables( $db->_originalTablePrefix, __METHOD__ );
1662 if ( $prefix === 'unprefixed' ) {
1663 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix, '/' ) . '/';
1664 $originalTables = array_map(
1665 function ( $pt ) use ( $originalPrefixRegex ) {
1666 return preg_replace( $originalPrefixRegex, '', $pt );
1667 },
1668 $originalTables
1669 );
1670 }
1671
1672 return $originalTables;
1673 }
1674
1675 /**
1676 * Re-clones the given mock tables to restore them based on the live database schema.
1677 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1678 * should be called first.
1679 *
1680 * @param IMaintainableDatabase $db
1681 * @param array $tables
1682 */
1683 private function recloneMockTables( IMaintainableDatabase $db, array $tables ) {
1684 $this->ensureMockDatabaseConnection( $db );
1685
1686 if ( !isset( $db->_originalTablePrefix ) ) {
1687 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1688 }
1689
1690 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1691 $tables = array_intersect( $tables, $originalTables );
1692
1693 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix );
1694 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1695
1696 $dbClone->cloneTableStructure();
1697 }
1698
1699 /**
1700 * Empty all tables so they can be repopulated for tests
1701 *
1702 * @param Database $db|null Database to reset
1703 * @param array $tablesUsed Tables to reset
1704 */
1705 private function resetDB( $db, $tablesUsed ) {
1706 if ( $db ) {
1707 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1708 $pageTables = [
1709 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1710 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1711 ];
1712 $coreDBDataTables = array_merge( $userTables, $pageTables );
1713
1714 // If any of the user or page tables were marked as used, we should clear all of them.
1715 if ( array_intersect( $tablesUsed, $userTables ) ) {
1716 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1717 TestUserRegistry::clear();
1718 }
1719 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1720 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1721 }
1722
1723 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1724 // instead of user/text. But Postgres does not remap the
1725 // table name in tableExists(), so we mark the real table
1726 // names as being used.
1727 if ( $db->getType() === 'postgres' ) {
1728 if ( in_array( 'user', $tablesUsed ) ) {
1729 $tablesUsed[] = 'mwuser';
1730 }
1731 if ( in_array( 'text', $tablesUsed ) ) {
1732 $tablesUsed[] = 'pagecontent';
1733 }
1734 }
1735
1736 foreach ( $tablesUsed as $tbl ) {
1737 $this->truncateTable( $tbl, $db );
1738 }
1739
1740 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1741 // Reset services that may contain information relating to the truncated tables
1742 $this->overrideMwServices();
1743 // Re-add core DB data that was deleted
1744 $this->addCoreDBData();
1745 }
1746 }
1747 }
1748
1749 /**
1750 * Empties the given table and resets any auto-increment counters.
1751 * Will also purge caches associated with some well known tables.
1752 * If the table is not know, this method just returns.
1753 *
1754 * @param string $tableName
1755 * @param IDatabase|null $db
1756 */
1757 protected function truncateTable( $tableName, IDatabase $db = null ) {
1758 if ( !$db ) {
1759 $db = $this->db;
1760 }
1761
1762 if ( !$db->tableExists( $tableName ) ) {
1763 return;
1764 }
1765
1766 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1767
1768 if ( $truncate ) {
1769 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__ );
1770 } else {
1771 $db->delete( $tableName, '*', __METHOD__ );
1772 }
1773
1774 if ( $db instanceof DatabasePostgres || $db instanceof DatabaseSqlite ) {
1775 // Reset the table's sequence too.
1776 $db->resetSequenceForTable( $tableName, __METHOD__ );
1777 }
1778
1779 // re-initialize site_stats table
1780 if ( $tableName === 'site_stats' ) {
1781 SiteStatsInit::doPlaceholderInit();
1782 }
1783 }
1784
1785 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1786 $tableName = substr( $tableName, strlen( $prefix ) );
1787 }
1788
1789 private static function isNotUnittest( $table ) {
1790 return strpos( $table, self::DB_PREFIX ) !== 0;
1791 }
1792
1793 /**
1794 * @since 1.18
1795 *
1796 * @param IMaintainableDatabase $db
1797 *
1798 * @return array
1799 */
1800 public static function listTables( IMaintainableDatabase $db ) {
1801 $prefix = $db->tablePrefix();
1802 $tables = $db->listTables( $prefix, __METHOD__ );
1803
1804 if ( $db->getType() === 'mysql' ) {
1805 static $viewListCache = null;
1806 if ( $viewListCache === null ) {
1807 $viewListCache = $db->listViews( null, __METHOD__ );
1808 }
1809 // T45571: cannot clone VIEWs under MySQL
1810 $tables = array_diff( $tables, $viewListCache );
1811 }
1812 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1813
1814 // Don't duplicate test tables from the previous fataled run
1815 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1816
1817 if ( $db->getType() == 'sqlite' ) {
1818 $tables = array_flip( $tables );
1819 // these are subtables of searchindex and don't need to be duped/dropped separately
1820 unset( $tables['searchindex_content'] );
1821 unset( $tables['searchindex_segdir'] );
1822 unset( $tables['searchindex_segments'] );
1823 $tables = array_flip( $tables );
1824 }
1825
1826 return $tables;
1827 }
1828
1829 /**
1830 * Copy test data from one database connection to another.
1831 *
1832 * This should only be used for small data sets.
1833 *
1834 * @param IDatabase $source
1835 * @param IDatabase $target
1836 */
1837 public function copyTestData( IDatabase $source, IDatabase $target ) {
1838 $tables = self::listOriginalTables( $source, 'unprefixed' );
1839
1840 foreach ( $tables as $table ) {
1841 $res = $source->select( $table, '*', [], __METHOD__ );
1842 $allRows = [];
1843
1844 foreach ( $res as $row ) {
1845 $allRows[] = (array)$row;
1846 }
1847
1848 $target->insert( $table, $allRows, __METHOD__, [ 'IGNORE' ] );
1849 }
1850 }
1851
1852 /**
1853 * @throws MWException
1854 * @since 1.18
1855 */
1856 protected function checkDbIsSupported() {
1857 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1858 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1859 }
1860 }
1861
1862 /**
1863 * @since 1.18
1864 * @param string $offset
1865 * @return mixed
1866 */
1867 public function getCliArg( $offset ) {
1868 return $this->cliArgs[$offset] ?? null;
1869 }
1870
1871 /**
1872 * @since 1.18
1873 * @param string $offset
1874 * @param mixed $value
1875 */
1876 public function setCliArg( $offset, $value ) {
1877 $this->cliArgs[$offset] = $value;
1878 }
1879
1880 /**
1881 * Don't throw a warning if $function is deprecated and called later
1882 *
1883 * @since 1.19
1884 *
1885 * @param string $function
1886 */
1887 public function hideDeprecated( $function ) {
1888 Wikimedia\suppressWarnings();
1889 wfDeprecated( $function );
1890 Wikimedia\restoreWarnings();
1891 }
1892
1893 /**
1894 * Asserts that the given database query yields the rows given by $expectedRows.
1895 * The expected rows should be given as indexed (not associative) arrays, with
1896 * the values given in the order of the columns in the $fields parameter.
1897 * Note that the rows are sorted by the columns given in $fields.
1898 *
1899 * @since 1.20
1900 *
1901 * @param string|array $table The table(s) to query
1902 * @param string|array $fields The columns to include in the result (and to sort by)
1903 * @param string|array $condition "where" condition(s)
1904 * @param array $expectedRows An array of arrays giving the expected rows.
1905 * @param array $options Options for the query
1906 * @param array $join_conds Join conditions for the query
1907 *
1908 * @throws MWException If this test cases's needsDB() method doesn't return true.
1909 * Test cases can use "@group Database" to enable database test support,
1910 * or list the tables under testing in $this->tablesUsed, or override the
1911 * needsDB() method.
1912 */
1913 protected function assertSelect(
1914 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1915 ) {
1916 if ( !$this->needsDB() ) {
1917 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1918 ' method should return true. Use @group Database or $this->tablesUsed.' );
1919 }
1920
1921 $db = wfGetDB( DB_REPLICA );
1922
1923 $res = $db->select(
1924 $table,
1925 $fields,
1926 $condition,
1927 wfGetCaller(),
1928 $options + [ 'ORDER BY' => $fields ],
1929 $join_conds
1930 );
1931 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1932
1933 $i = 0;
1934
1935 foreach ( $expectedRows as $expected ) {
1936 $r = $res->fetchRow();
1937 self::stripStringKeys( $r );
1938
1939 $i += 1;
1940 $this->assertNotEmpty( $r, "row #$i missing" );
1941
1942 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1943 }
1944
1945 $r = $res->fetchRow();
1946 self::stripStringKeys( $r );
1947
1948 $this->assertFalse( $r, "found extra row (after #$i)" );
1949 }
1950
1951 /**
1952 * Utility method taking an array of elements and wrapping
1953 * each element in its own array. Useful for data providers
1954 * that only return a single argument.
1955 *
1956 * @since 1.20
1957 *
1958 * @param array $elements
1959 *
1960 * @return array
1961 */
1962 protected function arrayWrap( array $elements ) {
1963 return array_map(
1964 function ( $element ) {
1965 return [ $element ];
1966 },
1967 $elements
1968 );
1969 }
1970
1971 /**
1972 * Assert that two arrays are equal. By default this means that both arrays need to hold
1973 * the same set of values. Using additional arguments, order and associated key can also
1974 * be set as relevant.
1975 *
1976 * @since 1.20
1977 *
1978 * @param array $expected
1979 * @param array $actual
1980 * @param bool $ordered If the order of the values should match
1981 * @param bool $named If the keys should match
1982 */
1983 protected function assertArrayEquals( array $expected, array $actual,
1984 $ordered = false, $named = false
1985 ) {
1986 if ( !$ordered ) {
1987 $this->objectAssociativeSort( $expected );
1988 $this->objectAssociativeSort( $actual );
1989 }
1990
1991 if ( !$named ) {
1992 $expected = array_values( $expected );
1993 $actual = array_values( $actual );
1994 }
1995
1996 call_user_func_array(
1997 [ $this, 'assertEquals' ],
1998 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1999 );
2000 }
2001
2002 /**
2003 * Put each HTML element on its own line and then equals() the results
2004 *
2005 * Use for nicely formatting of PHPUnit diff output when comparing very
2006 * simple HTML
2007 *
2008 * @since 1.20
2009 *
2010 * @param string $expected HTML on oneline
2011 * @param string $actual HTML on oneline
2012 * @param string $msg Optional message
2013 */
2014 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2015 $expected = str_replace( '>', ">\n", $expected );
2016 $actual = str_replace( '>', ">\n", $actual );
2017
2018 $this->assertEquals( $expected, $actual, $msg );
2019 }
2020
2021 /**
2022 * Does an associative sort that works for objects.
2023 *
2024 * @since 1.20
2025 *
2026 * @param array &$array
2027 */
2028 protected function objectAssociativeSort( array &$array ) {
2029 uasort(
2030 $array,
2031 function ( $a, $b ) {
2032 return serialize( $a ) <=> serialize( $b );
2033 }
2034 );
2035 }
2036
2037 /**
2038 * Utility function for eliminating all string keys from an array.
2039 * Useful to turn a database result row as returned by fetchRow() into
2040 * a pure indexed array.
2041 *
2042 * @since 1.20
2043 *
2044 * @param mixed &$r The array to remove string keys from.
2045 */
2046 protected static function stripStringKeys( &$r ) {
2047 if ( !is_array( $r ) ) {
2048 return;
2049 }
2050
2051 foreach ( $r as $k => $v ) {
2052 if ( is_string( $k ) ) {
2053 unset( $r[$k] );
2054 }
2055 }
2056 }
2057
2058 /**
2059 * Asserts that the provided variable is of the specified
2060 * internal type or equals the $value argument. This is useful
2061 * for testing return types of functions that return a certain
2062 * type or *value* when not set or on error.
2063 *
2064 * @since 1.20
2065 *
2066 * @param string $type
2067 * @param mixed $actual
2068 * @param mixed $value
2069 * @param string $message
2070 */
2071 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2072 if ( $actual === $value ) {
2073 $this->assertTrue( true, $message );
2074 } else {
2075 $this->assertType( $type, $actual, $message );
2076 }
2077 }
2078
2079 /**
2080 * Asserts the type of the provided value. This can be either
2081 * in internal type such as boolean or integer, or a class or
2082 * interface the value extends or implements.
2083 *
2084 * @since 1.20
2085 *
2086 * @param string $type
2087 * @param mixed $actual
2088 * @param string $message
2089 */
2090 protected function assertType( $type, $actual, $message = '' ) {
2091 if ( class_exists( $type ) || interface_exists( $type ) ) {
2092 $this->assertInstanceOf( $type, $actual, $message );
2093 } else {
2094 $this->assertInternalType( $type, $actual, $message );
2095 }
2096 }
2097
2098 /**
2099 * Returns true if the given namespace defaults to Wikitext
2100 * according to $wgNamespaceContentModels
2101 *
2102 * @param int $ns The namespace ID to check
2103 *
2104 * @return bool
2105 * @since 1.21
2106 */
2107 protected function isWikitextNS( $ns ) {
2108 global $wgNamespaceContentModels;
2109
2110 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2111 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2112 }
2113
2114 return true;
2115 }
2116
2117 /**
2118 * Returns the ID of a namespace that defaults to Wikitext.
2119 *
2120 * @throws MWException If there is none.
2121 * @return int The ID of the wikitext Namespace
2122 * @since 1.21
2123 */
2124 protected function getDefaultWikitextNS() {
2125 global $wgNamespaceContentModels;
2126
2127 static $wikitextNS = null; // this is not going to change
2128 if ( $wikitextNS !== null ) {
2129 return $wikitextNS;
2130 }
2131
2132 // quickly short out on most common case:
2133 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2134 return NS_MAIN;
2135 }
2136
2137 // NOTE: prefer content namespaces
2138 $namespaces = array_unique( array_merge(
2139 MWNamespace::getContentNamespaces(),
2140 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2141 MWNamespace::getValidNamespaces()
2142 ) );
2143
2144 $namespaces = array_diff( $namespaces, [
2145 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2146 ] );
2147
2148 $talk = array_filter( $namespaces, function ( $ns ) {
2149 return MWNamespace::isTalk( $ns );
2150 } );
2151
2152 // prefer non-talk pages
2153 $namespaces = array_diff( $namespaces, $talk );
2154 $namespaces = array_merge( $namespaces, $talk );
2155
2156 // check default content model of each namespace
2157 foreach ( $namespaces as $ns ) {
2158 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2159 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2160 ) {
2161 $wikitextNS = $ns;
2162
2163 return $wikitextNS;
2164 }
2165 }
2166
2167 // give up
2168 // @todo Inside a test, we could skip the test as incomplete.
2169 // But frequently, this is used in fixture setup.
2170 throw new MWException( "No namespace defaults to wikitext!" );
2171 }
2172
2173 /**
2174 * Check, if $wgDiff3 is set and ready to merge
2175 * Will mark the calling test as skipped, if not ready
2176 *
2177 * @since 1.21
2178 */
2179 protected function markTestSkippedIfNoDiff3() {
2180 global $wgDiff3;
2181
2182 # This check may also protect against code injection in
2183 # case of broken installations.
2184 Wikimedia\suppressWarnings();
2185 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2186 Wikimedia\restoreWarnings();
2187
2188 if ( !$haveDiff3 ) {
2189 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2190 }
2191 }
2192
2193 /**
2194 * Check if $extName is a loaded PHP extension, will skip the
2195 * test whenever it is not loaded.
2196 *
2197 * @since 1.21
2198 * @param string $extName
2199 * @return bool
2200 */
2201 protected function checkPHPExtension( $extName ) {
2202 $loaded = extension_loaded( $extName );
2203 if ( !$loaded ) {
2204 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2205 }
2206
2207 return $loaded;
2208 }
2209
2210 /**
2211 * Skip the test if using the specified database type
2212 *
2213 * @param string $type Database type
2214 * @since 1.32
2215 */
2216 protected function markTestSkippedIfDbType( $type ) {
2217 if ( $this->db->getType() === $type ) {
2218 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2219 }
2220 }
2221
2222 /**
2223 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2224 * @param string $buffer
2225 * @return string
2226 */
2227 public static function wfResetOutputBuffersBarrier( $buffer ) {
2228 return $buffer;
2229 }
2230
2231 /**
2232 * Create a temporary hook handler which will be reset by tearDown.
2233 * This replaces other handlers for the same hook.
2234 * @param string $hookName Hook name
2235 * @param mixed $handler Value suitable for a hook handler
2236 * @since 1.28
2237 */
2238 protected function setTemporaryHook( $hookName, $handler ) {
2239 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2240 }
2241
2242 /**
2243 * Check whether file contains given data.
2244 * @param string $fileName
2245 * @param string $actualData
2246 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2247 * and skip the test.
2248 * @param string $msg
2249 * @since 1.30
2250 */
2251 protected function assertFileContains(
2252 $fileName,
2253 $actualData,
2254 $createIfMissing = false,
2255 $msg = ''
2256 ) {
2257 if ( $createIfMissing ) {
2258 if ( !file_exists( $fileName ) ) {
2259 file_put_contents( $fileName, $actualData );
2260 $this->markTestSkipped( 'Data file $fileName does not exist' );
2261 }
2262 } else {
2263 self::assertFileExists( $fileName );
2264 }
2265 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2266 }
2267
2268 /**
2269 * Edits or creates a page/revision
2270 * @param string $pageName Page title
2271 * @param string $text Content of the page
2272 * @param string $summary Optional summary string for the revision
2273 * @param int $defaultNs Optional namespace id
2274 * @return array Array as returned by WikiPage::doEditContent()
2275 * @throws MWException If this test cases's needsDB() method doesn't return true.
2276 * Test cases can use "@group Database" to enable database test support,
2277 * or list the tables under testing in $this->tablesUsed, or override the
2278 * needsDB() method.
2279 */
2280 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
2281 if ( !$this->needsDB() ) {
2282 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2283 ' method should return true. Use @group Database or $this->tablesUsed.' );
2284 }
2285
2286 $title = Title::newFromText( $pageName, $defaultNs );
2287 $page = WikiPage::factory( $title );
2288
2289 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
2290 }
2291
2292 /**
2293 * Revision-deletes a revision.
2294 *
2295 * @param Revision|int $rev Revision to delete
2296 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2297 * clear, -1 to leave alone. (All other values also clear the bit.)
2298 * @param string $comment Deletion comment
2299 */
2300 protected function revisionDelete(
2301 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
2302 ) {
2303 if ( is_int( $rev ) ) {
2304 $rev = Revision::newFromId( $rev );
2305 }
2306 RevisionDeleter::createList(
2307 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
2308 )->setVisibility( [
2309 'value' => $value,
2310 'comment' => $comment,
2311 ] );
2312 }
2313 }