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