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