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