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