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