Debian Codegraph @

tests/phpunit/MediaWikiIntegrationTestCase.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Config\Config;
4 use MediaWiki\Config\ConfigFactory;
5 use MediaWiki\Config\HashConfig;
6 use MediaWiki\Config\MultiConfig;
7 use MediaWiki\Content\Content;
8 use MediaWiki\Content\ContentHandler;
9 use MediaWiki\Context\RequestContext;
10 use MediaWiki\Deferred\DeferredUpdates;
11 use MediaWiki\HookContainer\FauxGlobalHookArray;
12 use MediaWiki\HookContainer\HookRunner;
13 use MediaWiki\Language\Language;
14 use MediaWiki\Linker\LinkTarget;
15 use MediaWiki\Logger\LegacyLogger;
16 use MediaWiki\Logger\LegacySpi;
17 use MediaWiki\Logger\LogCapturingSpi;
18 use MediaWiki\Logger\LoggerFactory;
19 use MediaWiki\MainConfigNames;
20 use MediaWiki\MediaWikiServices;
21 use MediaWiki\Page\PageIdentity;
22 use MediaWiki\Page\ProperPageIdentity;
23 use MediaWiki\Parser\ParserOptions;
24 use MediaWiki\Permissions\Authority;
25 use MediaWiki\Permissions\UltimateAuthority;
26 use MediaWiki\Profiler\ProfilingContext;
27 use MediaWiki\Registration\ExtensionRegistry;
28 use MediaWiki\Request\FauxRequest;
29 use MediaWiki\Request\WebRequest;
30 use MediaWiki\Revision\RevisionRecord;
31 use MediaWiki\SiteStats\SiteStatsInit;
32 use MediaWiki\Storage\PageUpdateStatus;
33 use MediaWiki\Tests\Unit\DummyServicesTrait;
34 use MediaWiki\Title\Title;
35 use MediaWiki\User\User;
36 use MediaWiki\User\UserIdentityValue;
37 use Psr\Log\LoggerInterface;
38 use Psr\Log\NullLogger;
39 use Wikimedia\ObjectCache\BagOStuff;
40 use Wikimedia\ObjectCache\HashBagOStuff;
41 use Wikimedia\Rdbms\ChangedTablesTracker;
42 use Wikimedia\Rdbms\Database;
43 use Wikimedia\Rdbms\IDatabase;
44 use Wikimedia\Rdbms\IMaintainableDatabase;
45
46 /**
47 * @since 1.18
48 *
49 * Extend this class if you are testing classes which access global variables, methods, services
50 * or a storage backend.
51 *
52 * Consider using MediaWikiUnitTestCase and mocking dependencies if your code uses dependency
53 * injection and does not access any globals.
54 *
55 * Database changes and configuration changes will be rolled back at the end of each individual
56 * test.
57 *
58 * @stable to extend
59 */
60 abstract class MediaWikiIntegrationTestCase extends PHPUnit\Framework\TestCase {
61 use MediaWikiCoversValidator;
62 use MediaWikiGroupValidator;
63 use MediaWikiTestCaseTrait;
64 use DummyServicesTrait;
65
66 /**
67 * The original service locator. This is overridden during setUp().
68 *
69 * @var MediaWikiServices|null
70 */
71 private static $originalServices;
72
73 /**
74 * Cached service wirings of the original service locator, to work around T247990
75 * @var callable[]
76 */
77 private static $originalServiceWirings = [];
78
79 /**
80 * The local service locator, created during setUp().
81 * @var MediaWikiServices
82 */
83 private $localServices;
84
85 /**
86 * @var TestUser[]
87 * @since 1.20
88 * @deprecated since 1.41 Use Authority if possible, or call $this->getTestUser or getTestSysop directly.
89 */
90 public static $users;
91
92 /**
93 * DB_PRIMARY handle to the main database connection used for integration tests
94 *
95 * Test classes should generally use {@link getDb()} instead of this property
96 *
97 * @var Database|null
98 * @since 1.18
99 * @deprecated since 1.43. Use MediaWikiIntegrationTestCase->getDb() instead. This will
100 * eventually be made private.
101 */
102 protected $db;
103
104 /**
105 * Cloned database
106 *
107 * @var ?CloneDatabase
108 */
109 private static $dbClone = null;
110
111 /**
112 * @var array
113 * @since 1.19
114 * @deprecated since 1.41 Tables used are now detected automatically.
115 */
116 protected $tablesUsed = []; // tables with data
117
118 /** @var bool */
119 private static $useTemporaryTables = true;
120 /** @var bool */
121 private static $dbSetup = false;
122 /** @var string */
123 private static $oldTablePrefix = '';
124
125 /**
126 * Holds the paths of temporary files/directories created through getNewTempFile,
127 * and getNewTempDirectory
128 *
129 * @var array
130 */
131 private $tmpFiles = [];
132
133 /**
134 * Holds original values of MediaWiki configuration settings
135 * to be restored in tearDown().
136 * See also setMwGlobals().
137 * @var array
138 */
139 private $mwGlobals = [];
140
141 /**
142 * Holds a list of MediaWiki configuration settings to be unset in tearDown().
143 * See also setMwGlobals().
144 * @var array
145 */
146 private $mwGlobalsToUnset = [];
147
148 /**
149 * Holds original values of ini settings to be restored
150 * in tearDown().
151 * @see setIniSettings()
152 * @var array
153 */
154 private $iniSettings = [];
155
156 /**
157 * Holds original loggers which have been replaced by setLogger()
158 * @var LoggerInterface[]
159 */
160 private $loggers = [];
161
162 /**
163 * Holds original loggers which have been ignored by setNullLogger()
164 * @var array<array<LegacyLogger|int>>
165 */
166 private $ignoredLoggers = [];
167
168 /**
169 * Holds a list of services that were overridden with setService(). Used for printing an error
170 * if overrideMwServices() overrides a service that was previously set.
171 * @var string[]
172 */
173 private $overriddenServices = [];
174
175 /**
176 * @var ?HashConfig
177 */
178 private $overriddenConfig = null;
179
180 /**
181 * @var array[] contains temporary hooks as a list of name/handler pairs,
182 * where a name/false pair indicates the hook being cleared.
183 */
184 private $temporaryHookHandlers = [];
185
186 /**
187 * Table name prefix.
188 */
189 public const DB_PREFIX = 'unittest_';
190
191 private const SUPPORTED_DBS = [
192 'mysql',
193 'sqlite',
194 'postgres',
195 ];
196
197 /**
198 * @var array|null
199 * @todo Remove options for filebackend and jobqueue (they should have dedicated test subclasses), and simplify
200 * once it's just one setting.
201 */
202 private static ?array $additionalCliOptions;
203
204 /**
205 * @var string[] Used to store tables changed in the subclass addDBDataOnce method. These are only cleared in the
206 * tearDownAfterClass method.
207 */
208 private static array $dbDataOnceTables = [];
209
210 /**
211 * @stable to call
212 * @param string|null $name
213 * @param array $data
214 * @param string $dataName
215 */
216 public function __construct( $name = null, array $data = [], $dataName = '' ) {
217 parent::__construct( $name, $data, $dataName );
218
219 $this->backupGlobals = false;
220 $this->backupStaticAttributes = false;
221 }
222
223 /**
224 * The annotation causes this to be called immediately before setUpBeforeClass()
225 * @beforeClass
226 */
227 final public static function mediaWikiSetUpBeforeClass(): void {
228 $settingsFile = wfDetectLocalSettingsFile();
229 if ( !is_file( $settingsFile ) ) {
230 echo "The file $settingsFile could not be found. "
231 . "Test case " . static::class . " extends " . self::class . " "
232 . "which requires a working MediaWiki installation.\n"
233 . ( new RuntimeException() )->getTraceAsString();
234 die();
235 }
236
237 // Get the original service locator
238 if ( !self::$originalServices ) {
239 self::$originalServices = MediaWikiServices::getInstance();
240 }
241 }
242
243 /**
244 * The annotation causes this to be called immediately after tearDownAfterClass()
245 * @afterClass
246 */
247 final public static function mediaWikiTearDownAfterClass(): void {
248 if ( static::$dbDataOnceTables ) {
249 $db = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
250 self::resetDB( $db, self::$dbDataOnceTables );
251 }
252 }
253
254 /**
255 * Get a DB_PRIMARY database connection reference on the current testing domain
256 *
257 * Since temporary tables are typically used, it is important to stick to a single
258 * underlying connection. DBConnRef balances this concern while making sure that the
259 * DB domain used for each caller matches expectations.
260 *
261 * @return IDatabase
262 * @since 1.39
263 */
264 protected function getDb() {
265 if ( !self::needsDB() ) {
266 throw new LogicException( 'This test does not need DB but tried to access it anyway' );
267 }
268 return MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
269 }
270
271 /**
272 * Convenience method for getting an immutable test user
273 *
274 * @since 1.28
275 *
276 * @param string|string[] $groups User groups that the test user should be in.
277 * @return TestUser
278 */
279 protected function getTestUser( $groups = [] ) {
280 if ( !self::needsDB() ) {
281 throw new LogicException(
282 'Test users get persisted in the test database and can only be used in tests having ' .
283 '`@group Database`. Add this test to the Database group or, preferably, construct or ' .
284 'mock a UserIdentity/Authority if the test doesn\'t need a real user account.'
285 );
286 }
287 return TestUserRegistry::getImmutableTestUser( $groups );
288 }
289
290 /**
291 * Convenience method for getting a mutable test user
292 *
293 * @since 1.28
294 *
295 * @param string|string[] $groups User groups that the test user should be in.
296 * @param string|null $userPrefix String to use as a user name prefix
297 * @return TestUser
298 */
299 protected function getMutableTestUser( $groups = [], $userPrefix = null ) {
300 if ( !self::needsDB() ) {
301 throw new LogicException(
302 'Test users get persisted in the test database and can only be used in tests having ' .
303 '`@group Database`. Add this test to the Database group or, preferably, construct or ' .
304 'mock a UserIdentity/Authority if the test doesn\'t need a real user account.'
305 );
306 }
307
308 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups, $userPrefix );
309 }
310
311 /**
312 * Convenience method for getting an immutable admin test user
313 *
314 * @since 1.28
315 *
316 * @return TestUser
317 */
318 protected function getTestSysop() {
319 return $this->getTestUser( [ 'sysop', 'bureaucrat' ] );
320 }
321
322 /**
323 * Returns a WikiPage representing an existing page. This method requires database support, which can be enabled
324 * with "@group Database".
325 *
326 * @since 1.32
327 *
328 * @param Title|string|null $title
329 * @return WikiPage
330 */
331 protected function getExistingTestPage( $title = null ) {
332 if ( !self::needsDB() ) {
333 throw new LogicException( 'When testing with pages, the test must use @group Database' );
334 }
335
336 $caller = $this->getCallerName();
337 if ( !$title instanceof Title ) {
338 if ( $title === null ) {
339 static $counter;
340 $counter = $counter === null ? random_int( 10, 1000 ) : ++$counter;
341 $title = Title::newFromText( "Test page $counter $caller", $this->getDefaultWikitextNS() );
342 } else {
343 $title = Title::newFromText( $title );
344 }
345 }
346 if ( $title->getContentModel() !== CONTENT_MODEL_WIKITEXT ) {
347 throw new LogicException( "Requested page {$title->getPrefixedText()} isn't in the wikitext content model." );
348 }
349 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
350
351 if ( !$page->exists() ) {
352 $user = static::getTestSysop()->getUser();
353 $status = $page->doUserEditContent(
354 ContentHandler::makeContent(
355 "Test content for $caller",
356 $title
357 ),
358 $user,
359 "Summary for $caller",
360 EDIT_NEW | EDIT_SUPPRESS_RC
361 );
362 if ( !$status->isGood() ) {
363 throw new RuntimeException( "Could not create test page: $status" );
364 }
365 }
366
367 return $page;
368 }
369
370 /**
371 * Returns a WikiPage representing a non-existing page. This method requires database support, which can be enabled
372 * with "@group Database".
373 *
374 * @since 1.32
375 *
376 * @param Title|string|null $title
377 * @return WikiPage
378 */
379 protected function getNonexistingTestPage( $title = null ) {
380 if ( !self::needsDB() ) {
381 throw new LogicException( 'When testing with pages, the test must use @group Database.' );
382 }
383
384 $caller = $this->getCallerName();
385 if ( !( $title instanceof Title ) ) {
386 $title = Title::newFromText( $title ?? "Test page $caller " . wfRandomString() );
387 }
388 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
389 $page = $wikiPageFactory->newFromTitle( $title );
390
391 if ( $page->exists() ) {
392 $this->deletePage( $page, "Deleting for $caller" );
393 }
394
395 return $page;
396 }
397
398 /**
399 * Returns the calling method, in a format suitable for page titles etc.
400 *
401 * @return string
402 */
403 private function getCallerName(): string {
404 $classWithoutNamespace = ( new ReflectionClass( $this ) )->getShortName();
405 return $classWithoutNamespace . '-' . debug_backtrace()[2]['function'];
406 }
407
408 /**
409 * Determine config overrides, taking into account the local system's actual settings and
410 * avoiding interference with any custom overrides.
411 *
412 * @param Config|null $customOverrides Custom overrides that should take precedence
413 * over the default overrides. Settings from $customOverrides that conflict
414 * with a default override will replace that default override.
415 * @param Config|null $baseConfig Used to get the baseline value for settings.
416 * This is used when the override should only affect part of a setting
417 * that contains a complex structure, such as ObjectCache's.
418 * If not given, the original main config will be used.
419 * The base config will not be used as a fallback for config keys that are
420 * not overwritten, it is only used to determine the values of keys that are
421 * overwritten.
422 *
423 * @return array Config overrides
424 */
425 public static function getConfigOverrides(
426 ?Config $customOverrides = null,
427 ?Config $baseConfig = null
428 ): array {
429 $overrides = [];
430
431 if ( !$baseConfig ) {
432 if ( self::$originalServices ) {
433 $baseConfig = self::$originalServices->getMainConfig();
434 } else {
435 $baseConfig = MediaWikiServices::getInstance()->getMainConfig();
436 }
437 }
438
439 /* Some functions require some kind of caching, and will end up using the db,
440 * which we can't allow, as that would open a new connection for mysql.
441 * Replace with a HashBag. They would not be going to persist anyway.
442 */
443 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
444 $objectCaches = [
445 CACHE_DB => $hashCache,
446 CACHE_ACCEL => $hashCache,
447 CACHE_MEMCACHED => $hashCache,
448 'apc' => $hashCache,
449 'apcu' => $hashCache,
450 'UTCache' => $hashCache,
451 ] + $baseConfig->get( MainConfigNames::ObjectCaches );
452
453 // Use hash-based caches
454 $overrides[ MainConfigNames::ObjectCaches ] = $objectCaches;
455
456 // Use a hash-based BagOStuff as the main cache
457 $overrides[ MainConfigNames::MainCacheType ] = CACHE_HASH;
458
459 // Don't actually store jobs
460 $overrides[ MainConfigNames::JobTypeConf ] = [ 'default' => [ 'class' => JobQueueMemory::class ] ];
461
462 // Use a fast hash algorithm to hash passwords.
463 $overrides[ MainConfigNames::PasswordDefault ] = 'A';
464
465 // Since $overrides would shadow entries in $customOverrides, copy any
466 // conflicting entries from $customOverrides into $overrides.
467 // Later, $overrides and $customOverrides will be combined in a MultiConfig.
468 // If $customOverrides was an IterableConfig, we wouldn't need to do that,
469 // we could just copy it entirely into $overrides.
470 if ( $customOverrides ) {
471 foreach ( $overrides as $key => $dummy ) {
472 if ( $customOverrides->has( $key ) ) {
473 $overrides[ $key ] = $customOverrides->get( $key );
474 }
475 }
476 }
477
478 return $overrides;
479 }
480
481 /**
482 * @param ConfigFactory $oldFactory
483 * @param Config[] $configurations
484 *
485 * @return Closure
486 */
487 private static function makeTestConfigFactoryInstantiator(
488 ConfigFactory $oldFactory,
489 array $configurations
490 ) {
491 return static function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
492 $factory = new ConfigFactory();
493
494 // clone configurations from $oldFactory that are not overwritten by $configurations
495 $namesToClone = array_diff(
496 $oldFactory->getConfigNames(),
497 array_keys( $configurations )
498 );
499
500 foreach ( $namesToClone as $name ) {
501 $factory->register( $name, $oldFactory->makeConfig( $name ) );
502 }
503
504 foreach ( $configurations as $name => $config ) {
505 $factory->register( $name, $config );
506 }
507
508 return $factory;
509 };
510 }
511
512 /**
513 * Resets some non-service singleton instances and other static caches. It's not necessary to
514 * reset services here.
515 */
516 public static function resetNonServiceCaches() {
517 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
518 global $wgRequest, $wgJobClasses, $wgTitle;
519
520 /* Prevent global wgTitle state from carrying over between test cases
521 * @see T365130 */
522 $wgTitle = null;
523
524 $jobQueueFactory = MediaWikiServices::getInstance()->getJobQueueGroupFactory();
525
526 foreach ( $wgJobClasses as $type => $class ) {
527 $jobQueueFactory->makeJobQueueGroup()->get( $type )->delete();
528 }
529
530 MediaWikiServices::getInstance()->getObjectCacheFactory()->clear();
531 DeferredUpdates::clearPendingUpdates();
532
533 // TODO: move global state into MediaWikiServices
534 RequestContext::resetMain();
535 if ( session_id() !== '' ) {
536 session_write_close();
537 session_id( '' );
538 }
539
540 $wgRequest = RequestContext::getMain()->getRequest();
541 MediaWiki\Session\SessionManager::resetCache();
542
543 TestUserRegistry::clear();
544
545 // Invalidate any Title objects cached by newFromText() or isMainPage() (T395214).
546 Title::clearCaches();
547 }
548
549 /**
550 * @return bool
551 */
552 private static function oncePerClass( IDatabase $db ) {
553 // Remember the current test class in the database connection,
554 // so we know when we need to run addData.
555
556 $class = static::class;
557
558 $hasDataForTestClass = DynamicPropertyTestHelper::getDynamicProperty( $db, 'hasDataForTestClass' );
559
560 $first = $hasDataForTestClass !== $class;
561
562 DynamicPropertyTestHelper::setDynamicProperty( $db, 'hasDataForTestClass', $class );
563 return $first;
564 }
565
566 /**
567 * @since 1.21
568 *
569 * @return bool
570 */
571 public function usesTemporaryTables() {
572 return self::$useTemporaryTables;
573 }
574
575 /**
576 * Obtains a new temporary file name
577 *
578 * The obtained filename is enlisted to be removed upon tearDown
579 *
580 * @since 1.20
581 *
582 * @return string Absolute name of the temporary file
583 */
584 protected function getNewTempFile() {
585 $fileName = tempnam(
586 wfTempDir(),
587 // Avoid backslashes here as they result in inconsistent results
588 // between Windows and other OS, as well as between functions
589 // that try to normalise these in one or both directions.
590 // For example, tempnam rejects directory separators in the prefix, which
591 // means it rejects any namespaced class on Windows.
592 // And then there is, wfMkdirParents which normalises paths always
593 // whereas most other PHP and MW functions do not.
594 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
595 );
596 $this->tmpFiles[] = $fileName;
597
598 return $fileName;
599 }
600
601 /**
602 * Obtains a new temporary directory
603 *
604 * The obtained directory is enlisted to be removed (recursively with all its contained
605 * files) upon tearDown.
606 *
607 * @since 1.20
608 *
609 * @return string Absolute name of the temporary directory
610 */
611 protected function getNewTempDirectory() {
612 // Starting of with a temporary *file*.
613 $fileName = $this->getNewTempFile();
614
615 // Converting the temporary file to a *directory*.
616 // The following is not atomic, but at least we now have a single place,
617 // where temporary directory creation is bundled and can be improved.
618 unlink( $fileName );
619 // If this fails for some reason, PHP will warn and fail the test.
620 mkdir( $fileName, 0777, /* recursive = */ true );
621
622 return $fileName;
623 }
624
625 /**
626 * The annotation causes this to be called immediately before setUp()
627 * @before
628 */
629 final protected function mediaWikiSetUp(): void {
630 $reflection = new ReflectionClass( $this );
631 // TODO: Eventually we should assert for test presence in /integration/
632 if ( str_contains( $reflection->getFileName(), '/unit/' ) ) {
633 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
634 }
635 if ( $this->tablesUsed && !self::isTestInDatabaseGroup() ) {
636 throw new LogicException(
637 get_class( $this ) . ' defines $tablesUsed but is not in the Database group'
638 );
639 }
640
641 $this->overrideMwServices();
642 $this->maybeSetupDB();
643
644 $this->overriddenServices = [];
645 $this->temporaryHookHandlers = [];
646
647 // Cleaning up temporary files
648 foreach ( $this->tmpFiles as $fileName ) {
649 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
650 unlink( $fileName );
651 } elseif ( is_dir( $fileName ) ) {
652 wfRecursiveRemoveDir( $fileName );
653 }
654 }
655
656 if ( self::needsDB() && $this->db ) {
657 // Clean up open transactions
658 while ( $this->db->trxLevel() > 0 ) {
659 $this->db->rollback( __METHOD__, 'flush' );
660 }
661 }
662
663 // Reset all caches between tests.
664 self::resetNonServiceCaches();
665
666 // T46192 Do not attempt to send a real e-mail
667 $this->setTemporaryHook( 'AlternateUserMailer',
668 static function () {
669 return false;
670 }
671 );
672 ob_start( 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' );
673 }
674
675 private function maybeSetupDB(): void {
676 if ( !self::needsDB() ) {
677 $this->getServiceContainer()->disableStorage();
678 // ReadOnlyMode calls ILoadBalancer::getReadOnlyReason(), which would throw an exception.
679 // However, very few tests actually need a real ReadOnlyMode, and those are probably
680 // already using a mock object, so override the service here.
681 $this->setService( 'ReadOnlyMode', $this->getDummyReadOnlyMode( false ) );
682 $this->db = null;
683 return;
684 }
685 // Set up a DB connection for this test to use
686 $useTemporaryTables = !self::getCliArg( 'use-normal-tables' );
687
688 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
689 // Need a Database where the DB domain changes during table cloning
690 $this->db = $lb->getConnectionInternal( DB_PRIMARY );
691
692 if ( !self::$dbSetup ) {
693 self::checkDbIsSupported( $this->db );
694 self::setupAllTestDBs(
695 $this->db, self::dbPrefix(), $useTemporaryTables
696 );
697 // Several tests might want to assume there is an initialized site_stats row
698 SiteStatsInit::doPlaceholderInit();
699 }
700
701 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
702 // is available in subclass's setUpBeforeClass() and setUp() methods.
703 // This would also remove the need for the HACK that is oncePerClass().
704 if ( self::oncePerClass( $this->db ) ) {
705 $this->setUpSchema( $this->db );
706 ChangedTablesTracker::startTracking();
707 $this->addDBDataOnce();
708 static::$dbDataOnceTables = ChangedTablesTracker::getTables( $this->db->getDomainID() );
709 ChangedTablesTracker::stopTracking();
710 }
711
712 ChangedTablesTracker::startTracking();
713 $this->addDBData();
714 }
715
716 protected function addTmpFiles( $files ) {
717 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
718 }
719
720 /**
721 * The annotation causes this to be called immediately after tearDown()
722 * @after
723 */
724 final protected function mediaWikiTearDown(): void {
725 global $wgRequest;
726
727 $status = ob_get_status();
728 if ( isset( $status['name'] ) &&
729 $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier'
730 ) {
731 ob_end_flush();
732 }
733
734 if ( self::needsDB() && $this->db ) {
735 // Clean up open transactions
736 while ( $this->db->trxLevel() > 0 ) {
737 $this->db->rollback( __METHOD__, 'flush' );
738 }
739 }
740
741 // Clear any cached test users so they don't retain references to old services
742 TestUserRegistry::clear();
743
744 // Restore config
745 if ( $this->overriddenConfig ) {
746 $this->overriddenConfig->clear();
747 }
748
749 // Restore mw globals
750 foreach ( $this->mwGlobals as $key => $value ) {
751 $GLOBALS[$key] = $value;
752 }
753 foreach ( $this->mwGlobalsToUnset as $value ) {
754 unset( $GLOBALS[$value] );
755 }
756 foreach ( $this->iniSettings as $name => $value ) {
757 ini_set( $name, $value );
758 }
759 $this->mwGlobals = [];
760 $this->mwGlobalsToUnset = [];
761 $this->restoreLoggers();
762
763 // Cleaning up temporary files - after logger, if temp files used there
764 foreach ( $this->tmpFiles as $fileName ) {
765 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
766 unlink( $fileName );
767 } elseif ( is_dir( $fileName ) ) {
768 wfRecursiveRemoveDir( $fileName );
769 }
770 }
771
772 // TODO: move global state into MediaWikiServices
773 RequestContext::resetMain();
774 if ( session_id() !== '' ) {
775 session_write_close();
776 session_id( '' );
777 }
778 $wgRequest = RequestContext::getMain()->getRequest();
779 MediaWiki\Session\SessionManager::resetCache();
780 ProfilingContext::destroySingleton();
781
782 // If anything changed the content language, we need to
783 // reset the SpecialPageFactory.
784 MediaWikiServices::getInstance()->resetServiceForTesting(
785 'SpecialPageFactory'
786 );
787
788 // We don't mind if we override already-overridden services during cleanup
789 $this->overriddenServices = [];
790 $this->temporaryHookHandlers = [];
791
792 if ( self::needsDB() ) {
793 $tablesUsed = ChangedTablesTracker::getTables( $this->db->getDomainID() );
794 ChangedTablesTracker::stopTracking();
795 // Do not clear tables written by addDBDataOnce, otherwise the data would need to be added again every time.
796 $tablesUsed = array_diff( $tablesUsed, static::$dbDataOnceTables );
797 self::resetDB( $this->db, $tablesUsed );
798 }
799
800 self::restoreMwServices();
801 $this->localServices = null;
802 }
803
804 /**
805 * Gets the service container to be used with integration tests.
806 *
807 * @return MediaWikiServices
808 * @since 1.36
809 */
810 protected function getServiceContainer() {
811 if ( !$this->localServices ) {
812 throw new LogicException( __METHOD__ . ' must be called after MediaWikiIntegrationTestCase::run()' );
813 }
814
815 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
816 throw new UnexpectedValueException( __METHOD__ . ' may lead to inconsistencies because the '
817 . ' global MediaWikiServices instance has been replaced by test code.' );
818 }
819
820 return $this->localServices;
821 }
822
823 /**
824 * Get a configuration variable
825 *
826 * @param string $name
827 * @return mixed
828 * @since 1.38
829 */
830 protected function getConfVar( $name ) {
831 return $this->getServiceContainer()->getMainConfig()->get( $name );
832 }
833
834 /**
835 * Sets a service, maintaining a stashed version of the previous service to be
836 * restored in tearDown.
837 *
838 * @note This calls resetServices() in case any other services depend on the set service(s).
839 *
840 * @param string $name
841 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
842 * @param object|callable $service The service instance, or a callable that returns the service instance.
843 *
844 * @since 1.27
845 *
846 */
847 protected function setService( string $name, $service ) {
848 if ( !$this->localServices ) {
849 throw new LogicException( __METHOD__ . ' must be called after MediaWikiIntegrationTestCase::run()' );
850 }
851
852 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
853 throw new UnexpectedValueException( __METHOD__ . ' will not work because the global MediaWikiServices '
854 . 'instance has been replaced by test code.' );
855 }
856
857 $instantiator = is_callable( $service ) ? $service : static fn () => $service;
858
859 $this->overriddenServices[] = $name;
860
861 $this->localServices->disableService( $name );
862 $this->localServices->redefineService(
863 $name,
864 $instantiator
865 );
866
867 $this->resetServices();
868 }
869
870 /**
871 * Sets a MediaWiki config global, maintaining a stashed version of the previous global to be
872 * restored in tearDown
873 *
874 * The key is added to the array of globals that will be reset after in the tearDown().
875 *
876 * @note Since 1.39, use overrideConfigValue() to override configuration.
877 * Since then, setMwGlobals() should only be used for the rare case of global variables
878 * that are not configuration.
879 *
880 * @param array|string $pairs Key to the global variable, or an array
881 * of key/value pairs.
882 * @param mixed|null $value Value to set the global to (ignored
883 * if an array is given as first argument).
884 *
885 * @since 1.21
886 */
887 protected function setMwGlobals( $pairs, $value = null ) {
888 if ( is_string( $pairs ) ) {
889 $pairs = [ $pairs => $value ];
890 }
891
892 $this->stashMwGlobals( array_keys( $pairs ) );
893
894 $identical = true;
895 foreach ( $pairs as $key => $val ) {
896 // T317951: Don't use array_key_exists for performance reasons
897 if ( !isset( $GLOBALS[$key] ) || $GLOBALS[$key] !== $val ) {
898 $GLOBALS[$key] = $val;
899 $identical = false;
900 }
901 }
902
903 if ( !$identical ) {
904 $this->resetServices();
905 }
906 }
907
908 /**
909 * Overrides a config setting for the duration of the current test case.
910 * The original value of the config setting will be restored after the test case finishes.
911 *
912 * @note This will cause any existing service instances to be reset.
913 *
914 * @see setMwGlobals
915 * @see \MediaWiki\Settings\SettingsBuilder::overrideConfigValue
916 *
917 * @par Example
918 * @code
919 * protected function setUp() : void {
920 * parent::setUp();
921 * $this->overrideConfigValue( MainConfigNames::RestrictStuff, true );
922 * }
923 *
924 * function testFoo() {}
925 *
926 * function testBar() {}
927 * $this->assertTrue( self::getX()->doStuff() );
928 *
929 * $this->overrideConfigValue( MainConfigNames::RestrictStuff, false );
930 * $this->assertTrue( self::getX()->doStuff() );
931 * }
932 *
933 * function testQuux() {}
934 * @endcode
935 *
936 * @param string $key
937 * @param mixed $value
938 *
939 * @since 1.39
940 */
941 protected function overrideConfigValue( string $key, $value ) {
942 $this->overriddenConfig->set( $key, $value );
943
944 // When nothing reads config from globals anymore, we will no longer need to call
945 // setMwGlobals() here.
946 $this->setMwGlobals( "wg$key", $value );
947 }
948
949 /**
950 * Set the main object cache that will be returned by ObjectCache::getLocalClusterInstance().
951 *
952 * By default, the main object cache is disabled during testing (that is, the cache is an
953 * EmptyBagOStuff).
954 *
955 * The $cache parameter supports the following kinds of values:
956 * - a string: refers to an entry in the ObjectCaches array, see MainConfigSchema::ObjectCaches.
957 * MainCacheType will be set to this value. Use CACHE_HASH to use a HashBagOStuff.
958 * - an int: refers to an entry in the ObjectCaches array, see MainConfigSchema::ObjectCaches.
959 * MainCacheType will be set to this value. Use CACHE_NONE to disable caching.
960 * - a BagOStuff: the object will be injected into the ObjectCache class under the name
961 * 'UTCache', and MainCacheType will be set to 'UTCache'.
962 *
963 * @note Most entries in the ObjectCaches config setting are overwritten during testing.
964 * To set the cache to anything other than CACHE_HASH, you will have to override
965 * the ObjectCaches setting first.
966 *
967 * @note This will cause any existing service instances to be reset.
968 *
969 * @param string|int|BagOStuff $cache
970 * @return string|int The new value of the MainCacheType setting.
971 */
972 protected function setMainCache( $cache ) {
973 if ( $cache instanceof BagOStuff ) {
974 $cacheId = 'UTCache';
975 $objectCaches = $this->getConfVar( MainConfigNames::ObjectCaches );
976 $objectCaches[$cacheId] = [
977 'factory' => static function () use ( $cache ) {
978 return $cache;
979 }
980 ];
981 $this->overrideConfigValue( MainConfigNames::ObjectCaches, $objectCaches );
982 } else {
983 $cacheId = $cache;
984 }
985
986 if ( !is_string( $cacheId ) && !is_int( $cacheId ) ) {
987 throw new InvalidArgumentException( 'Bad type of $cache parameter: ' . get_debug_type( $cacheId ) );
988 }
989
990 $this->overrideConfigValue( MainConfigNames::MainCacheType, $cacheId );
991 return $cacheId;
992 }
993
994 /**
995 * Overrides a set of config settings for the duration of the current test case.
996 * The original values of the config settings will be restored after the test case finishes.
997 *
998 * @note This will cause any existing service instances to be reset.
999 *
1000 * @see setMwGlobals
1001 * @see \MediaWiki\Settings\SettingsBuilder::overrideConfigValues
1002 *
1003 * @param array<string,mixed> $values
1004 *
1005 * @since 1.39
1006 */
1007 protected function overrideConfigValues( array $values ) {
1008 $vars = [];
1009
1010 foreach ( $values as $key => $value ) {
1011 $this->overriddenConfig->set( $key, $value );
1012 $var = "wg$key";
1013 $vars[$var] = $value;
1014 }
1015
1016 // When nothing reads config from globals anymore, we will no longer need to call
1017 // setMwGlobals() here.
1018 $this->setMwGlobals( $vars );
1019 }
1020
1021 /**
1022 * Set the global request in the two places it is stored.
1023 * @param WebRequest $request
1024 * @since 1.36
1025 */
1026 protected function setRequest( $request ) {
1027 global $wgRequest;
1028 // It's not necessary to stash the value with setMwGlobals(), since
1029 // it's reset on teardown anyway.
1030 $wgRequest = $request;
1031 RequestContext::getMain()->setRequest( $request );
1032 }
1033
1034 /**
1035 * Set an ini setting for the duration of the test
1036 * @param string $name Name of the setting
1037 * @param string $value Value to set
1038 * @since 1.32
1039 */
1040 protected function setIniSetting( $name, $value ) {
1041 $original = ini_get( $name );
1042 $this->iniSettings[$name] = $original;
1043 ini_set( $name, $value );
1044 }
1045
1046 /**
1047 * Check if we can back up a value by performing a shallow copy.
1048 * Values which fail this test are copied recursively.
1049 *
1050 * @param mixed $value
1051 * @return bool True if a shallow copy is ok for this purpose; false if a deep copy
1052 * is required.
1053 */
1054 private static function canShallowCopy( $value ) {
1055 if ( is_scalar( $value ) || $value === null ) {
1056 return true;
1057 }
1058 if ( is_array( $value ) ) {
1059 foreach ( $value as $subValue ) {
1060 if ( !is_scalar( $subValue ) && $subValue !== null ) {
1061 return false;
1062 }
1063 }
1064 return true;
1065 }
1066 return false;
1067 }
1068
1069 /**
1070 * Stash the values of globals which the test is going to modify.
1071 * Stashed values will be restored on test tear-down.
1072 *
1073 * @since 1.38
1074 * @param string[] $globalKeys
1075 */
1076 protected function stashMwGlobals( $globalKeys ) {
1077 if ( is_string( $globalKeys ) ) {
1078 $globalKeys = [ $globalKeys ];
1079 }
1080
1081 foreach ( $globalKeys as $globalKey ) {
1082 // NOTE: make sure we only save the global once or a second call to
1083 // setMwGlobals() on the same global would override the original
1084 // value.
1085 if (
1086 !array_key_exists( $globalKey, $this->mwGlobals ) &&
1087 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
1088 ) {
1089 // (T317951) Don't call array_key_exists unless we have to, as it's slow
1090 // on PHP 8.1+ for $GLOBALS. When the key is set but is explicitly set
1091 // to null, we still need to fall back to array_key_exists, but that's rarer.
1092 if ( !isset( $GLOBALS[$globalKey] ) && !array_key_exists( $globalKey, $GLOBALS ) ) {
1093 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
1094 continue;
1095 }
1096 // NOTE: we serialize then unserialize the value in case it is an object
1097 // this stops any objects being passed by reference. We could use clone
1098 // and if is_object but this does account for objects within objects!
1099 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
1100 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
1101 } elseif (
1102 // Many MediaWiki types are safe to clone. These are the
1103 // ones that are most commonly stashed.
1104 $GLOBALS[$globalKey] instanceof Language ||
1105 $GLOBALS[$globalKey] instanceof User ||
1106 $GLOBALS[$globalKey] instanceof FauxRequest
1107 ) {
1108 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
1109 } else {
1110 try {
1111 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
1112 } catch ( Exception $e ) {
1113 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
1114 }
1115 }
1116 }
1117 }
1118 }
1119
1120 /**
1121 * Merges the given values into a MediaWiki global array variable.
1122 * Useful for setting some entries in a configuration array, instead of
1123 * setting the entire array.
1124 *
1125 * @param string $name The name of the global, as in wgFooBar
1126 * @param array $values The array containing the entries to set in that global
1127 *
1128 * @note This will call resetServices().
1129 *
1130 * @since 1.21
1131 */
1132 protected function mergeMwGlobalArrayValue( $name, $values ) {
1133 if ( !isset( $GLOBALS[$name] ) ) {
1134 $merged = $values;
1135 } else {
1136 // NOTE: do not use array_merge, it screws up for numeric keys.
1137 $merged = $GLOBALS[$name];
1138
1139 // HACK for fake $wgHooks. Replace it with the original array here,
1140 // then let resetLegacyGlobals() turn it back into a fake.
1141 if ( $merged instanceof FauxGlobalHookArray ) {
1142 $merged = $merged->getOriginalArray();
1143 }
1144
1145 if ( !is_array( $merged ) ) {
1146 throw new RuntimeException( "MW global $name is not an array." );
1147 }
1148
1149 foreach ( $values as $k => $v ) {
1150 $merged[$k] = $v;
1151 }
1152 }
1153
1154 $this->setMwGlobals( $name, $merged );
1155 }
1156
1157 /**
1158 * Resets service instances in the global instance of MediaWikiServices.
1159 *
1160 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
1161 * and it preserves any service instances set via setService().
1162 *
1163 * The primary use case for this method is to allow changes to global configuration variables
1164 * to take effect on services that get initialized based on these global configuration
1165 * variables. It is called by setMwGlobals/overrideConfigValues
1166 *
1167 * @see MediaWikiServices::resetServiceForTesting.
1168 *
1169 * @since 1.34
1170 */
1171 protected function resetServices() {
1172 // Reset but don't destroy service instances supplied via setService().
1173 $oldHookContainer = $this->localServices->getHookContainer();
1174 foreach ( $this->overriddenServices as $name ) {
1175 $this->localServices->resetServiceForTesting( $name, false );
1176 }
1177
1178 // Reset all services with the destroy flag set.
1179 // This will not have any effect on services that had already been reset above.
1180 foreach ( $this->localServices->getServiceNames() as $name ) {
1181 $this->localServices->resetServiceForTesting( $name, true );
1182 }
1183
1184 // If the hook container was reset, re-apply temporary hooks.
1185 $newHookContainer = $this->localServices->getHookContainer();
1186 if ( $newHookContainer !== $oldHookContainer ) {
1187 // the same hook may be cleared and registered several times
1188 foreach ( $this->temporaryHookHandlers as [ $name, $target ] ) {
1189 if ( !$target ) {
1190 $newHookContainer->clear( $name );
1191 } else {
1192 $newHookContainer->register( $name, $target );
1193 }
1194 }
1195 }
1196
1197 self::resetLegacyGlobals( $this->localServices );
1198 }
1199
1200 /**
1201 * Installs a new global instance of MediaWikiServices, allowing test cases to override
1202 * settings and services.
1203 *
1204 * This method can be used to set up specific services or configuration as a fixture.
1205 * It should not be used to reset services in between stages of a test - instead, the test
1206 * should either be split, or resetServices() should be used.
1207 *
1208 * If called with no parameters, this method restores all services to their default state.
1209 * This is done automatically before each test to isolate tests from any modification
1210 * to settings and services that may have been applied by previous tests.
1211 * That means that the effect of calling overrideMwServices() is undone before the next
1212 * call to a test method.
1213 *
1214 * @note Calling this after having called setService() in the same test method (or the
1215 * associated setUp) will result in an exception.
1216 * Tests should use either overrideMwServices() or setService(), but not mix both.
1217 * Since 1.34, resetServices() is available as an alternative compatible with setService().
1218 *
1219 * @param Config|null $customOverrides Custom configuration overrides for the new MediaWikiServices
1220 * instance.
1221 * @param callable[] $services An associative array of services to re-define. Keys are service
1222 * names, values are callables.
1223 *
1224 * @return MediaWikiServices
1225 * @since 1.27
1226 */
1227 protected function overrideMwServices(
1228 ?Config $customOverrides = null, array $services = []
1229 ) {
1230 if ( $this->overriddenServices ) {
1231 throw new LogicException(
1232 'The following services were set and are now being unset by overrideMwServices: ' .
1233 implode( ', ', $this->overriddenServices )
1234 );
1235 }
1236
1237 $this->overriddenConfig = new HashConfig();
1238
1239 // Create the Config object that will be stacked on top of the real bootstrap config
1240 // to create the config that will be used as the bootstrap as well as the main config
1241 // by the service container.
1242 // overrideConfigValue() will write to $this->overriddenConfig later and reset
1243 // services as appropriate.
1244 // Make sure that $this->overriddenConfig is the top layer of overrides.
1245 // XXX: If $customOverrides was guaranteed to be an IterableConfig, this could be
1246 // simplified by making getConfigOverrides() copy it into the $configOverrides array.
1247 // Or we could just get rid of $customOverrides.
1248 if ( $customOverrides ) {
1249 $serviceConfig = new MultiConfig( [ $this->overriddenConfig, $customOverrides ] );
1250 } else {
1251 $serviceConfig = $this->overriddenConfig;
1252 }
1253
1254 // NOTE: $serviceConfig doesn't have the overrides yet, they will be added
1255 // by calling overrideConfigValues() below.
1256 $newInstance = self::installMockMwServices( $serviceConfig );
1257
1258 if ( $this->localServices ) {
1259 $this->localServices->destroy();
1260 }
1261
1262 $this->localServices = $newInstance;
1263
1264 // Determine the config overrides that should apply during testing.
1265 $configOverrides = self::getConfigOverrides( $customOverrides );
1266
1267 $this->overrideConfigValues( $configOverrides );
1268
1269 foreach ( $services as $name => $callback ) {
1270 $newInstance->redefineService( $name, $callback );
1271 }
1272
1273 self::resetLegacyGlobals( $newInstance );
1274
1275 return $newInstance;
1276 }
1277
1278 /**
1279 * Creates a new "mock" MediaWikiServices instance, and installs it.
1280 * This effectively resets all cached states in services, with the exception of
1281 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1282 * the original MediaWikiServices.
1283 *
1284 * @warning This method interacts with the global state in a complex way. There should
1285 * generally be no need to call it directly. Subclasses should use more specific methods
1286 * like setService() or overrideConfigValues() instead.
1287 *
1288 * @note The new original MediaWikiServices instance can later be restored by calling
1289 * restoreMwServices(). That original is determined by the first call to this method, or
1290 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1291 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1292 * replaced when calling this method.
1293 *
1294 * @param Config|array|null $configOverrides Configuration overrides for the new
1295 * MediaWikiServices instance. This should be constructed by calling getConfigOverrides(),
1296 * to ensure that the configuration is safe for testing.
1297 *
1298 * @return MediaWikiServices the new mock service locator.
1299 */
1300 public static function installMockMwServices( $configOverrides = null ) {
1301 // Make sure we have the original service locator
1302 if ( !self::$originalServices ) {
1303 self::$originalServices = MediaWikiServices::getInstance();
1304 }
1305
1306 if ( $configOverrides === null ) {
1307 // Only use the default overrides if $configOverrides is not given.
1308 // Don't try to be smart and combine the custom overrides with the default overrides.
1309 // This gives overrideMwServices() full control over the configuration when it calls
1310 // this method.
1311 $configOverrides = self::getConfigOverrides();
1312 }
1313
1314 if ( is_array( $configOverrides ) ) {
1315 $configOverrides = new HashConfig( $configOverrides );
1316 }
1317
1318 // (T247990) Cache the original service wiring to work around a memory leak on PHP 7.4 and above
1319 if ( !self::$originalServiceWirings ) {
1320 $serviceWiringFiles = self::$originalServices->getBootstrapConfig()->get( MainConfigNames::ServiceWiringFiles );
1321
1322 foreach ( $serviceWiringFiles as $wiringFile ) {
1323 self::$originalServiceWirings[] = require $wiringFile;
1324 }
1325 }
1326
1327 $oldConfigFactory = self::$originalServices->getConfigFactory();
1328 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
1329
1330 $originalConfig = self::$originalServices->getBootstrapConfig();
1331 $testConfig = new MultiConfig( [ $configOverrides, $originalConfig ] );
1332
1333 $newServices = new MediaWikiServices( $testConfig );
1334
1335 // Load the default wiring from the specified files.
1336 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance
1337 if ( $configOverrides && $configOverrides->has( MainConfigNames::ServiceWiringFiles ) ) {
1338 $wiringFiles = $configOverrides->get( MainConfigNames::ServiceWiringFiles );
1339 $newServices->loadWiringFiles( $wiringFiles );
1340 } else {
1341 // (T247990) Avoid including default wiring many times - use the cached wiring
1342 foreach ( self::$originalServiceWirings as $wiring ) {
1343 $newServices->applyWiring( $wiring );
1344 }
1345 }
1346
1347 // Provide a traditional hook point to allow extensions to be able to configure services.
1348 $newServices->getHookContainer()->run( 'MediaWikiServices', [ $newServices ] );
1349
1350 // Use bootstrap config for all configuration.
1351 // This allows config overrides via global variables to take effect.
1352 $bootstrapConfig = $newServices->getBootstrapConfig();
1353 $newServices->resetServiceForTesting( 'ConfigFactory' );
1354 $newServices->redefineService(
1355 'ConfigFactory',
1356 self::makeTestConfigFactoryInstantiator(
1357 $oldConfigFactory,
1358 [ 'main' => $bootstrapConfig ]
1359 )
1360 );
1361 $newServices->resetServiceForTesting( 'LocalServerObjectCache' );
1362 $newServices->redefineService(
1363 'LocalServerObjectCache',
1364 static function ( MediaWikiServices $services ) {
1365 return $services->getObjectCacheFactory()->getInstance( 'hash' );
1366 }
1367 );
1368 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1369 $newServices->redefineService(
1370 'DBLoadBalancerFactory',
1371 static function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
1372 return $oldLoadBalancerFactory;
1373 }
1374 );
1375
1376 // Prevent real HTTP requests from tests
1377 $newServices->resetServiceForTesting( 'HttpRequestFactory' );
1378 $newServices->redefineService(
1379 'HttpRequestFactory',
1380 static function ( MediaWikiServices $services ) {
1381 return new NullHttpRequestFactory();
1382 }
1383 );
1384
1385 MediaWikiServices::forceGlobalInstance( $newServices );
1386
1387 self::resetLegacyGlobals( $newServices );
1388
1389 return $newServices;
1390 }
1391
1392 /**
1393 * Restores the original, non-mock MediaWikiServices instance.
1394 * The previously active MediaWikiServices instance is destroyed,
1395 * if it is different from the original that is to be restored.
1396 *
1397 * @note this if for internal use by test framework code. It should never be
1398 * called from inside a test case, a data provider, or a setUp or tearDown method.
1399 *
1400 * @return bool true if the original service locator was restored,
1401 * false if there was nothing too do.
1402 */
1403 public static function restoreMwServices() {
1404 if ( !self::$originalServices ) {
1405 return false;
1406 }
1407
1408 $currentServices = MediaWikiServices::getInstance();
1409
1410 if ( self::$originalServices === $currentServices ) {
1411 return false;
1412 }
1413
1414 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1415 $currentServices->destroy();
1416
1417 self::resetLegacyGlobals( self::$originalServices );
1418
1419 return true;
1420 }
1421
1422 private static function resetLegacyGlobals( MediaWikiServices $services ) {
1423 // phpcs:disable MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgHooks
1424 global $wgHooks;
1425
1426 $hooks = $wgHooks instanceof FauxGlobalHookArray ? $wgHooks->getOriginalArray() : $wgHooks;
1427
1428 $wgHooks = new FauxGlobalHookArray(
1429 $services->getHookContainer(),
1430 $hooks
1431 );
1432
1433 ParserOptions::clearStaticCache();
1434
1435 // User objects may hold service references!
1436 RequestContext::getMain()->getUser()->clearInstanceCache();
1437
1438 TestUserRegistry::clearInstanceCaches();
1439 }
1440
1441 /**
1442 * @since 1.27
1443 *
1444 * @param string|Language $lang
1445 */
1446 public function setUserLang( $lang ) {
1447 RequestContext::getMain()->setLanguage( $lang );
1448 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
1449 }
1450
1451 /**
1452 * @deprecated since 1.35. To change the site language, use
1453 * overrideConfigValue( MainConfigNames::LanguageCode ), which will also reset the service.
1454 * If you want to set the service to a specific object (like a mock), use
1455 * setService( 'ContentLanguage' ).
1456 *
1457 * @since 1.27
1458 *
1459 * @param string|Language $lang
1460 */
1461 public function setContentLang( $lang ) {
1462 if ( $lang instanceof Language ) {
1463 // Set to the exact object requested
1464 $this->setService( 'ContentLanguage', $lang );
1465 $this->overrideConfigValue( MainConfigNames::LanguageCode, $lang->getCode() );
1466 } else {
1467 $this->overrideConfigValue( MainConfigNames::LanguageCode, $lang );
1468 }
1469 }
1470
1471 /**
1472 * Alters $wgGroupPermissions for the duration of the test. Can be called
1473 * with an array, like
1474 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1475 * or three values to set a single permission, like
1476 * $this->setGroupPermissions( '*', 'read', false );
1477 *
1478 * @note This will call resetServices().
1479 *
1480 * @since 1.31
1481 *
1482 * @param array|string $newPerms Either an array of permissions to change,
1483 * in which case, the next two parameters are ignored; or a single string
1484 * identifying a group, to use with the next two parameters.
1485 * @param string|null $newKey
1486 * @param mixed|null $newValue
1487 */
1488 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1489 if ( is_string( $newPerms ) ) {
1490 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1491 }
1492
1493 $newPermissions = $this->getConfVar( MainConfigNames::GroupPermissions );
1494
1495 foreach ( $newPerms as $group => $permissions ) {
1496 foreach ( $permissions as $key => $value ) {
1497 $newPermissions[$group][$key] = $value;
1498 }
1499 }
1500
1501 $this->overrideConfigValue( MainConfigNames::GroupPermissions, $newPermissions );
1502 }
1503
1504 /**
1505 * Overrides specific user permissions until services are reloaded
1506 *
1507 * @since 1.34
1508 *
1509 * @param User $user
1510 * @param string[]|string $permissions
1511 *
1512 * @throws Exception
1513 */
1514 public function overrideUserPermissions( $user, $permissions = [] ) {
1515 MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1516 $user,
1517 $permissions
1518 );
1519 }
1520
1521 /**
1522 * Set the logger for a specified channel, for the duration of the test.
1523 *
1524 * @since 1.27
1525 *
1526 * @param string $channel
1527 * @param LoggerInterface $logger
1528 */
1529 protected function setLogger( $channel, LoggerInterface $logger ) {
1530 // TODO: Once loggers are managed by MediaWikiServices, use
1531 // resetServiceForTesting() to set loggers.
1532
1533 $provider = LoggerFactory::getProvider();
1534 if ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1535 $prev = $provider->setLoggerForTest( $channel, $logger );
1536 if ( !isset( $this->loggers[$channel] ) ) {
1537 // Remember for restoreLoggers()
1538 $this->loggers[$channel] = $prev;
1539 }
1540 } else {
1541 throw new LogicException( __METHOD__ . ': cannot set logger for ' . get_class( $provider ) );
1542 }
1543 }
1544
1545 /**
1546 * Restore loggers replaced by setLogger() or setNullLogger().
1547 *
1548 * @since 1.27
1549 */
1550 private function restoreLoggers() {
1551 $provider = LoggerFactory::getProvider();
1552 if ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1553 foreach ( $this->loggers as $channel => $logger ) {
1554 // Replace override with original object or null
1555 $provider->setLoggerForTest( $channel, $logger );
1556 }
1557 }
1558 $this->loggers = [];
1559
1560 foreach (
1561 array_splice( $this->ignoredLoggers, 0 )
1562 as [ $logger, $level ]
1563 ) {
1564 $logger->setMinimumForTest( $level );
1565 }
1566 }
1567
1568 /**
1569 * Ignore all messages for the specified log channel.
1570 *
1571 * This is an alternative to setLogger() for when an existing logger
1572 * must be changed as well (T248195).
1573 *
1574 * @since 1.35
1575 *
1576 * @param string $channel
1577 */
1578 protected function setNullLogger( $channel ) {
1579 $spi = LoggerFactory::getProvider();
1580 $spiCapture = null;
1581 if ( $spi instanceof LogCapturingSpi ) {
1582 $spiCapture = $spi;
1583 $spi = $spiCapture->getInnerSpi();
1584 }
1585 if ( !$spi instanceof LegacySpi ) {
1586 throw new LogicException( __METHOD__ . ': cannot set logger for ' . get_class( $spi ) );
1587 }
1588
1589 $existing = $spi->getLogger( $channel );
1590 $level = $existing->setMinimumForTest( null );
1591 $this->ignoredLoggers[] = [ $existing, $level ];
1592 if ( $spiCapture ) {
1593 $spiCapture->setLoggerForTest( $channel, new NullLogger() );
1594 // Remember to unset in restoreLoggers()
1595 $this->loggers[$channel] = null;
1596 }
1597 }
1598
1599 /**
1600 * @since 1.18
1601 *
1602 * @return string
1603 */
1604 final protected static function dbPrefix() {
1605 return self::DB_PREFIX;
1606 }
1607
1608 /**
1609 * @since 1.18
1610 *
1611 * @return bool
1612 */
1613 final protected static function needsDB() {
1614 static $needsDB = [];
1615 return $needsDB[static::class] ??= self::isTestInDatabaseGroup();
1616 }
1617
1618 /**
1619 * Insert a new page. This method requires database support, which can be enabled with "@group Database".
1620 *
1621 * Should be called from addDBData().
1622 *
1623 * @since 1.25 ($namespace in 1.28)
1624 * @param string|Title $title Page name or title
1625 * @param string $text Page's content
1626 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1627 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1628 * @return array Title object and page id
1629 */
1630 protected function insertPage(
1631 $title,
1632 $text = 'Sample page for unit test.',
1633 $namespace = null,
1634 ?User $user = null
1635 ) {
1636 if ( !self::needsDB() ) {
1637 throw new RuntimeException( 'When testing with pages, the test must use @group Database.' );
1638 }
1639
1640 if ( is_string( $title ) ) {
1641 $title = Title::newFromText( $title, $namespace );
1642 }
1643
1644 if ( !$user ) {
1645 $user = static::getTestSysop()->getUser();
1646 }
1647 $comment = __METHOD__ . ': Sample page for unit test.';
1648
1649 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
1650 $status = $page->doUserEditContent( ContentHandler::makeContent( $text, $title ), $user, $comment );
1651 if ( !$status->isOK() ) {
1652 $this->fail( $status->getWikiText() );
1653 }
1654
1655 return [
1656 'title' => $title,
1657 'id' => $page->getId(),
1658 ];
1659 }
1660
1661 /**
1662 * Stub. If a test suite needs to add additional data to the database, it should
1663 * implement this method and do so. This method is called once per test suite
1664 * (once per class).
1665 *
1666 * All tables touched by this method will not be cleared until the end of the test class.
1667 *
1668 * To add additional data between test function runs, override addDBData().
1669 *
1670 * @see addDBData()
1671 * @see resetDB()
1672 *
1673 * @since 1.27
1674 * @stable to override
1675 */
1676 public function addDBDataOnce() {
1677 }
1678
1679 /**
1680 * Stub. Subclasses may override this to prepare the database.
1681 * Called before every test run (test function or data set).
1682 *
1683 * @see addDBDataOnce()
1684 * @see resetDB()
1685 *
1686 * @since 1.18
1687 * @stable to override
1688 */
1689 public function addDBData() {
1690 }
1691
1692 /**
1693 * Restores MediaWiki to using the table set (table prefix) it was using before
1694 * setupTestDB() was called. Useful if we need to perform database operations
1695 * after the test run has finished (such as saving logs).
1696 *
1697 * This is called by phpunit/bootstrap.php after the last test.
1698 *
1699 * @since 1.21
1700 */
1701 public static function teardownTestDB() {
1702 global $wgJobClasses;
1703
1704 if ( !self::$dbSetup ) {
1705 return;
1706 }
1707
1708 $services = MediaWikiServices::getInstance();
1709 ( new HookRunner( $services->getHookContainer() ) )->onUnitTestsBeforeDatabaseTeardown();
1710
1711 $jobQueueGroup = $services->getJobQueueGroup();
1712 foreach ( $wgJobClasses as $type => $class ) {
1713 // Delete any jobs under the clone DB (or old prefix in other stores)
1714 $jobQueueGroup->get( $type )->delete();
1715 }
1716
1717 if ( self::$dbClone ) {
1718 self::$dbClone->destroy( true );
1719 self::$dbClone = null;
1720 }
1721
1722 // T219673: close any lingering connections.
1723 $services->getDBLoadBalancerFactory()->closeAll( __METHOD__ );
1724 CloneDatabase::changePrefix( self::$oldTablePrefix );
1725
1726 self::$oldTablePrefix = false;
1727 self::$dbSetup = false;
1728 }
1729
1730 /**
1731 * Setups a database with cloned tables using the given prefix.
1732 *
1733 * @param IMaintainableDatabase $db Database to use
1734 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1735 * automatically for $db.
1736 * @return CloneDatabase|null A CloneDatabase object if tables were cloned,
1737 * or null if the connection has already had its tables cloned.
1738 */
1739 protected static function setupDatabaseWithTestPrefix(
1740 IMaintainableDatabase $db,
1741 $prefix = null
1742 ) {
1743 $prefix ??= self::dbPrefix();
1744 $originalTablePrefix = DynamicPropertyTestHelper::getDynamicProperty( $db, 'originalTablePrefix' );
1745
1746 if ( $originalTablePrefix !== null ) {
1747 return null;
1748 }
1749
1750 $oldPrefix = $db->tablePrefix();
1751 if ( $oldPrefix === $prefix ) {
1752 // table already has the correct prefix, but presumably no cloned tables
1753 $oldPrefix = self::$oldTablePrefix;
1754 }
1755
1756 $db->tablePrefix( $oldPrefix );
1757 $tablesCloned = self::listTables( $db );
1758 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1759 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1760 $dbClone->cloneTableStructure();
1761
1762 $db->tablePrefix( $prefix );
1763 DynamicPropertyTestHelper::setDynamicProperty( $db, 'originalTablePrefix', $oldPrefix );
1764
1765 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
1766 $lb->setTempTablesOnlyMode( self::$useTemporaryTables, $db->getDomainID() );
1767 return $dbClone;
1768 }
1769
1770 public static function setupAllTestDBs( $db, ?string $testPrefix = null, ?bool $useTemporaryTables = null ) {
1771 global $wgDBprefix;
1772
1773 self::$oldTablePrefix = $wgDBprefix;
1774
1775 $testPrefix ??= self::dbPrefix();
1776
1777 // switch to a temporary clone of the database
1778 self::$useTemporaryTables = $useTemporaryTables ?? self::$useTemporaryTables;
1779 self::setupTestDB( $db, $testPrefix );
1780
1781 if ( self::isUsingExternalStoreDB() ) {
1782 self::setupExternalStoreTestDBs( $testPrefix );
1783 }
1784
1785 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1786 // *any* database connections to operate on live data.
1787 CloneDatabase::changePrefix( $testPrefix );
1788 }
1789
1790 /**
1791 * Creates an empty skeleton of the wiki database by cloning its structure
1792 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1793 * use the new set of tables (aka schema) instead of the original set.
1794 *
1795 * This is used to generate a dummy table set, typically consisting of temporary
1796 * tables, that will be used by tests instead of the original wiki database tables.
1797 *
1798 * @since 1.21
1799 *
1800 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1801 * by teardownTestDB() to return the wiki to using the original table set.
1802 *
1803 * @note this method only works when first called. Subsequent calls have no effect,
1804 * even if using different parameters.
1805 *
1806 * @param IMaintainableDatabase $db The database connection
1807 * @param string $prefix The prefix to use for the new table set (aka schema).
1808 */
1809 public static function setupTestDB( IMaintainableDatabase $db, $prefix ) {
1810 if ( self::$dbSetup ) {
1811 return;
1812 }
1813
1814 if ( $db->tablePrefix() === $prefix ) {
1815 throw new BadMethodCallException(
1816 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1817 }
1818
1819 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1820 // and Database no longer use global state.
1821
1822 $dbClone = self::setupDatabaseWithTestPrefix( $db, $prefix );
1823 if ( $dbClone ) {
1824 self::$dbClone = $dbClone;
1825 }
1826
1827 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onUnitTestsAfterDatabaseSetup( $db, $prefix );
1828
1829 self::$dbSetup = true;
1830 }
1831
1832 /**
1833 * Clones the External Store database(s) for testing
1834 *
1835 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1836 * if not given.
1837 */
1838 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1839 $connections = self::getExternalStoreDatabaseConnections();
1840 foreach ( $connections as $dbw ) {
1841 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1842 }
1843 }
1844
1845 /**
1846 * Gets primary database connections for all the ExternalStoreDB
1847 * stores configured in $wgDefaultExternalStore.
1848 *
1849 * @return Database[] Array of Database primary connections
1850 */
1851 protected static function getExternalStoreDatabaseConnections() {
1852 global $wgDefaultExternalStore;
1853
1854 /** @var ExternalStoreDB $externalStoreDB */
1855 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1856 $defaultArray = (array)$wgDefaultExternalStore;
1857 $dbws = [];
1858 foreach ( $defaultArray as $url ) {
1859 if ( str_starts_with( $url, 'DB://' ) ) {
1860 [ $proto, $cluster ] = explode( '://', $url, 2 );
1861 // Avoid getPrimary() because setupDatabaseWithTestPrefix()
1862 // requires Database instead of plain DBConnRef/IDatabase
1863 $dbws[] = $externalStoreDB->getPrimary( $cluster );
1864 }
1865 }
1866
1867 return $dbws;
1868 }
1869
1870 /**
1871 * Check whether ExternalStoreDB is being used
1872 *
1873 * @return bool True if it's being used
1874 */
1875 protected static function isUsingExternalStoreDB() {
1876 global $wgDefaultExternalStore;
1877 if ( !$wgDefaultExternalStore ) {
1878 return false;
1879 }
1880
1881 $defaultArray = (array)$wgDefaultExternalStore;
1882 foreach ( $defaultArray as $url ) {
1883 if ( str_starts_with( $url, 'DB://' ) ) {
1884 return true;
1885 }
1886 }
1887
1888 return false;
1889 }
1890
1891 /**
1892 * @throws LogicException if the given database connection is not set-up to use
1893 * mock tables.
1894 *
1895 * @since 1.31 this is no longer private.
1896 *
1897 * @param IDatabase $db
1898 */
1899 protected static function ensureMockDatabaseConnection( IDatabase $db ) {
1900 $testPrefix = self::dbPrefix();
1901 if ( $db->tablePrefix() !== $testPrefix ) {
1902 throw new LogicException(
1903 "Trying to delete mock tables, but table prefix '{$db->tablePrefix()}' " .
1904 "does not indicate a mock database (expected '$testPrefix')"
1905 );
1906 }
1907 }
1908
1909 private const SCHEMA_OVERRIDE_DEFAULTS = [
1910 'scripts' => [],
1911 'create' => [],
1912 'drop' => [],
1913 'alter' => [],
1914 ];
1915
1916 /**
1917 * Stub. If a test suite needs to test against a specific database schema, it should
1918 * override this method and return the appropriate information from it.
1919 *
1920 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1921 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1922 * the overrides may not be fully cleaned up, leading to errors later.
1923 *
1924 * @stable to override
1925 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1926 * May be used to check the current state of the schema, to determine what
1927 * overrides are needed.
1928 *
1929 * @return array An associative array with the following fields:
1930 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1931 * - 'create': A list of tables created (may or may not exist in the original schema).
1932 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1933 * - 'alter': A list of tables altered (expected to be present in the original schema).
1934 */
1935 protected function getSchemaOverrides( IMaintainableDatabase $db ) {
1936 return [];
1937 }
1938
1939 /**
1940 * Undoes the specified schema overrides.
1941 * Called once per test class, just before addDataOnce().
1942 *
1943 * @param IMaintainableDatabase $db
1944 * @param array $oldOverrides
1945 */
1946 private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOverrides ) {
1947 self::ensureMockDatabaseConnection( $db );
1948
1949 $oldOverrides = $oldOverrides + self::SCHEMA_OVERRIDE_DEFAULTS;
1950 $originalTables = self::listOriginalTables( $db );
1951
1952 // Drop tables that need to be restored or removed.
1953 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1954
1955 // Restore tables that have been dropped or created or altered,
1956 // if they exist in the original schema.
1957 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1958 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1959
1960 if ( $tablesToDrop ) {
1961 self::dropMockTables( $db, $tablesToDrop );
1962 }
1963
1964 if ( $tablesToRestore ) {
1965 $this->recloneMockTables( $db, $tablesToRestore );
1966 }
1967 }
1968
1969 /**
1970 * Applies the schema overrides returned by getSchemaOverrides(),
1971 * after undoing any previously applied schema overrides.
1972 * Called once per test class, just before addDataOnce().
1973 * @param IMaintainableDatabase $db
1974 */
1975 private function setUpSchema( IMaintainableDatabase $db ) {
1976 // Undo any active overrides.
1977 $oldOverrides = DynamicPropertyTestHelper::getDynamicProperty( $db, 'activeSchemaOverrides' ) ?? self::SCHEMA_OVERRIDE_DEFAULTS;
1978
1979 if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) {
1980 $this->undoSchemaOverrides( $db, $oldOverrides );
1981 DynamicPropertyTestHelper::unsetDynamicProperty( $db, 'activeSchemaOverrides' );
1982 }
1983
1984 // Determine new overrides.
1985 $overrides = $this->getSchemaOverrides( $db ) + self::SCHEMA_OVERRIDE_DEFAULTS;
1986
1987 $extraKeys = array_diff(
1988 array_keys( $overrides ),
1989 array_keys( self::SCHEMA_OVERRIDE_DEFAULTS )
1990 );
1991
1992 if ( $extraKeys ) {
1993 throw new InvalidArgumentException(
1994 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1995 );
1996 }
1997
1998 if ( !$overrides['scripts'] ) {
1999 // no scripts to run
2000 return;
2001 }
2002
2003 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
2004 throw new InvalidArgumentException(
2005 'Schema override scripts given, but no tables are declared to be '
2006 . 'created, dropped or altered.'
2007 );
2008 }
2009
2010 self::ensureMockDatabaseConnection( $db );
2011
2012 // Drop the tables that will be created by the schema scripts.
2013 $originalTables = self::listOriginalTables( $db );
2014 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
2015
2016 if ( $tablesToDrop ) {
2017 self::dropMockTables( $db, $tablesToDrop );
2018 }
2019
2020 $inputCallback = self::$useTemporaryTables
2021 ? static function ( $cmd ) {
2022 return preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd );
2023 }
2024 : null;
2025
2026 // Run schema override scripts.
2027 foreach ( $overrides['scripts'] as $script ) {
2028 $db->sourceFile( $script, null, null, __METHOD__, $inputCallback );
2029 }
2030
2031 DynamicPropertyTestHelper::setDynamicProperty( $db, 'activeSchemaOverrides', $overrides );
2032 }
2033
2034 /**
2035 * Drops the given mock tables.
2036 *
2037 * @param IMaintainableDatabase $db
2038 * @param array $tables
2039 */
2040 private static function dropMockTables( IMaintainableDatabase $db, array $tables ) {
2041 self::ensureMockDatabaseConnection( $db );
2042
2043 foreach ( $tables as $tbl ) {
2044 $tbl = $db->tableName( $tbl );
2045 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
2046 }
2047 }
2048
2049 /**
2050 * Lists all tables in the live database schema, without a prefix.
2051 *
2052 * @param IMaintainableDatabase $db
2053 * @return array
2054 */
2055 private static function listOriginalTables( IMaintainableDatabase $db ) {
2056 $originalTablePrefix = DynamicPropertyTestHelper::getDynamicProperty( $db, 'originalTablePrefix' );
2057 if ( $originalTablePrefix === null ) {
2058 throw new LogicException( 'No original table prefix know, cannot list tables!' );
2059 }
2060
2061 $originalTables = $db->listTables( $originalTablePrefix, __METHOD__ );
2062
2063 $unittestPrefixRegex = '/^' . preg_quote( self::dbPrefix(), '/' ) . '/';
2064 $originalPrefixRegex = '/^' . preg_quote( $originalTablePrefix, '/' ) . '/';
2065
2066 $originalTables = array_filter(
2067 $originalTables,
2068 static function ( $pt ) use ( $unittestPrefixRegex ) {
2069 return !preg_match( $unittestPrefixRegex, $pt );
2070 }
2071 );
2072
2073 $originalTables = array_map(
2074 static function ( $pt ) use ( $originalPrefixRegex ) {
2075 return preg_replace( $originalPrefixRegex, '', $pt );
2076 },
2077 $originalTables
2078 );
2079
2080 return array_unique( $originalTables );
2081 }
2082
2083 /**
2084 * Re-clones the given mock tables to restore them based on the live database schema.
2085 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
2086 * should be called first.
2087 *
2088 * @param IMaintainableDatabase $db
2089 * @param array $tables
2090 */
2091 private function recloneMockTables( IMaintainableDatabase $db, array $tables ) {
2092 self::ensureMockDatabaseConnection( $db );
2093
2094 $originalTablePrefix = DynamicPropertyTestHelper::getDynamicProperty( $db, 'originalTablePrefix' );
2095
2096 if ( $originalTablePrefix === null ) {
2097 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
2098 }
2099
2100 $originalTables = self::listOriginalTables( $db );
2101 $tables = array_intersect( $tables, $originalTables );
2102
2103 self::$dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $originalTablePrefix );
2104 self::$dbClone->useTemporaryTables( self::$useTemporaryTables );
2105 self::$dbClone->cloneTableStructure();
2106
2107 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2108 $lb->setTempTablesOnlyMode( self::$useTemporaryTables, $db->getDomainID() );
2109 }
2110
2111 /**
2112 * Empty all tables so they can be repopulated for tests
2113 *
2114 * @param IDatabase $db Database to reset
2115 * @param string[] $tablesUsed Tables to reset
2116 */
2117 private static function resetDB( IDatabase $db, array $tablesUsed ) {
2118 if ( !$tablesUsed ) {
2119 return;
2120 }
2121
2122 if ( in_array( 'user', $tablesUsed ) ) {
2123 TestUserRegistry::clear();
2124
2125 // Reset context user, which is probably 127.0.0.1, as its loaded
2126 // data is probably not valid. This used to manipulate $wgUser but
2127 // since that is deprecated tests are more likely to be relying on
2128 // RequestContext::getMain() instead.
2129 // @todo Should we start setting the user to something nondeterministic
2130 // to encourage tests to be updated to not depend on it?
2131 $user = RequestContext::getMain()->getUser();
2132 $user->clearInstanceCache( $user->mFrom );
2133 }
2134
2135 self::truncateTables( $tablesUsed, $db );
2136 }
2137
2138 protected function truncateTable( $table, ?IDatabase $db = null ) {
2139 self::truncateTables( [ $table ], $db );
2140 }
2141
2142 /**
2143 * Empties the given tables and resets any auto-increment counters.
2144 * Will also purge caches associated with some well-known tables.
2145 * If the table is not known, this method just returns.
2146 *
2147 * @param string[] $tables
2148 * @param IDatabase|null $db
2149 */
2150 protected static function truncateTables( array $tables, ?IDatabase $db = null ) {
2151 $dbw = $db ?: MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2152 foreach ( $tables as $table ) {
2153 $dbw->truncateTable( $table, __METHOD__ );
2154 }
2155
2156 // re-initialize site_stats table
2157 if ( in_array( 'site_stats', $tables ) ) {
2158 SiteStatsInit::doPlaceholderInit();
2159 }
2160 }
2161
2162 /**
2163 * @since 1.18
2164 * @param IMaintainableDatabase $db
2165 * @return array
2166 */
2167 public static function listTables( IMaintainableDatabase $db ) {
2168 $prefix = $db->tablePrefix();
2169 $tables = $db->listTables( $prefix, __METHOD__ );
2170
2171 $ret = [];
2172 foreach ( $tables as $table ) {
2173 // Remove the table prefix
2174 $table = substr( $table, strlen( $prefix ) );
2175
2176 // Don't duplicate test tables from the previous fatal run
2177 if ( str_starts_with( $table, self::DB_PREFIX ) ||
2178 str_starts_with( $table, ParserTestRunner::DB_PREFIX )
2179 ) {
2180 continue;
2181 }
2182
2183 // searchindex tables don't need to be duped/dropped separately
2184 if ( $db->getType() == 'sqlite' &&
2185 in_array( $table, [ 'searchindex_content', 'searchindex_segdir', 'searchindex_segments' ] )
2186 ) {
2187 continue;
2188 }
2189
2190 $ret[] = $table;
2191 }
2192
2193 return $ret;
2194 }
2195
2196 /**
2197 * Copy test data from one database connection to another.
2198 *
2199 * This should only be used for small data sets.
2200 *
2201 * @param IMaintainableDatabase $source
2202 * @param IMaintainableDatabase $target
2203 */
2204 public function copyTestData( IMaintainableDatabase $source, IMaintainableDatabase $target ) {
2205 if ( $this->db->getType() === 'sqlite' ) {
2206 // SQLite uses a non-temporary copy of the searchindex table for testing,
2207 // which gets deleted and re-created when setting up the secondary connection,
2208 // causing "Error 17" when trying to copy the data. See T191863#4130112.
2209 throw new RuntimeException(
2210 'Setting up a secondary database connection with test data is currently not supported'
2211 . ' with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
2212 );
2213 }
2214
2215 $tables = self::listOriginalTables( $source );
2216
2217 foreach ( $tables as $table ) {
2218 $res = $source->newSelectQueryBuilder()
2219 ->select( '*' )
2220 ->from( $table )
2221 ->caller( __METHOD__ )
2222 ->fetchResultSet();
2223 if ( !$res->numRows() ) {
2224 continue;
2225 }
2226 $allRows = [];
2227
2228 foreach ( $res as $row ) {
2229 $allRows[] = (array)$row;
2230 }
2231
2232 $target->newInsertQueryBuilder()
2233 ->insertInto( $table )
2234 ->ignore()
2235 ->rows( $allRows )
2236 ->caller( __METHOD__ )
2237 ->execute();
2238 }
2239 }
2240
2241 private static function checkDbIsSupported( IDatabase $db ) {
2242 if ( !in_array( $db->getType(), self::SUPPORTED_DBS ) ) {
2243 throw new RuntimeException( $db->getType() . " is not currently supported for unit testing." );
2244 }
2245 }
2246
2247 private static function maybeInitCliArgs(): void {
2248 self::$additionalCliOptions ??= [
2249 'use-normal-tables' => (bool)getenv( 'PHPUNIT_USE_NORMAL_TABLES' ),
2250 'use-jobqueue' => getenv( 'PHPUNIT_USE_JOBQUEUE' ) ?: null,
2251 ];
2252 }
2253
2254 /**
2255 * @since 1.18
2256 *
2257 * @param string $offset
2258 * @return mixed
2259 */
2260 protected static function getCliArg( $offset ) {
2261 self::maybeInitCliArgs();
2262 return self::$additionalCliOptions[$offset] ?? null;
2263 }
2264
2265 /**
2266 * @since 1.18
2267 *
2268 * @param string $offset
2269 * @param mixed $value
2270 */
2271 protected static function setCliArg( $offset, $value ) {
2272 self::maybeInitCliArgs();
2273 self::$additionalCliOptions[$offset] = $value;
2274 }
2275
2276 /**
2277 * Asserts that the given database query yields the rows given by $expectedRows.
2278 * The expected rows should be given as indexed (not associative) arrays, with
2279 * the values given in the order of the columns in the $fields parameter.
2280 * Note that the rows are sorted by the columns given in $fields.
2281 *
2282 * This method requires database support, which can be enabled with "@group Database".
2283 *
2284 * @since 1.20
2285 *
2286 * @param string|array $table The table(s) to query
2287 * @param string|array $fields The columns to include in the result (and to sort by)
2288 * @param string|array $condition "where" condition(s)
2289 * @param array $expectedRows An array of arrays giving the expected rows.
2290 * @param array $options Options for the query
2291 * @param array $join_conds Join conditions for the query
2292 */
2293 protected function assertSelect(
2294 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2295 ) {
2296 if ( !self::needsDB() ) {
2297 throw new LogicException( 'When testing database state, the test must use @group Database.' );
2298 }
2299
2300 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2301 $tables = is_array( $table ) ? $table : [ $table ];
2302 $conds = $condition === '' || $condition === '*' ? [] : $condition;
2303
2304 $res = $dbr->newSelectQueryBuilder()
2305 ->tables( $tables )
2306 ->fields( $fields )
2307 ->conds( $conds )
2308 ->caller( wfGetCaller() )
2309 ->options( $options )
2310 ->orderBy( $fields )
2311 ->joinConds( $join_conds )
2312 ->fetchResultSet();
2313
2314 $i = 0;
2315
2316 foreach ( $expectedRows as $expected ) {
2317 $r = $res->fetchRow();
2318 self::stripStringKeys( $r );
2319
2320 $i++;
2321 $this->assertNotFalse( $r, "row #$i missing" );
2322
2323 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2324 }
2325
2326 $r = $res->fetchRow();
2327 self::stripStringKeys( $r );
2328
2329 $this->assertFalse( $r, "found extra row (after #$i)" );
2330 }
2331
2332 /**
2333 * Get a SelectQueryBuilder with additional assert methods.
2334 *
2335 * This method requires database support, which can be enabled with "@group Database".
2336 *
2337 * @return TestSelectQueryBuilder
2338 */
2339 protected function newSelectQueryBuilder() {
2340 if ( !self::needsDB() ) {
2341 throw new LogicException( 'When testing database state, the test mut use @group Database.' );
2342 }
2343 return new TestSelectQueryBuilder( $this->getDb() );
2344 }
2345
2346 /**
2347 * Assert that an associative array contains the subset of an expected array.
2348 *
2349 * The internal key order does not matter.
2350 * Values are compared with strict equality.
2351 *
2352 * @since 1.35
2353 *
2354 * @param array $expected
2355 * @param array $actual
2356 * @param string $message
2357 */
2358 protected function assertArraySubmapSame(
2359 array $expected,
2360 array $actual,
2361 $message = ''
2362 ) {
2363 $this->assertArrayContains( $expected, $actual, $message );
2364 }
2365
2366 /**
2367 * Utility method taking an array of elements and wrapping
2368 * each element in its own array. Useful for data providers
2369 * that only return a single argument.
2370 *
2371 * @since 1.20
2372 *
2373 * @param array $elements
2374 *
2375 * @return array
2376 */
2377 protected function arrayWrap( array $elements ) {
2378 return array_map(
2379 static function ( $element ) {
2380 return [ $element ];
2381 },
2382 $elements
2383 );
2384 }
2385
2386 /**
2387 * Utility function for eliminating all string keys from an array.
2388 * Useful to turn a database result row as returned by fetchRow() into
2389 * a pure indexed array.
2390 *
2391 * @since 1.20
2392 * @internal
2393 *
2394 * @param mixed &$r The array to remove string keys from.
2395 */
2396 public static function stripStringKeys( &$r ) {
2397 if ( !is_array( $r ) ) {
2398 return;
2399 }
2400
2401 foreach ( $r as $k => $v ) {
2402 if ( is_string( $k ) ) {
2403 unset( $r[$k] );
2404 }
2405 }
2406 }
2407
2408 /**
2409 * Returns true if the given namespace defaults to Wikitext
2410 * according to $wgNamespaceContentModels
2411 *
2412 * @since 1.21
2413 *
2414 * @param int $ns The namespace ID to check
2415 * @return bool
2416 */
2417 protected function isWikitextNS( $ns ) {
2418 global $wgNamespaceContentModels;
2419
2420 return !isset( $wgNamespaceContentModels[$ns] ) ||
2421 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2422 }
2423
2424 /**
2425 * Returns the ID of a namespace that defaults to Wikitext.
2426 *
2427 * @since 1.21
2428 *
2429 * @return int The ID of the wikitext Namespace
2430 */
2431 protected function getDefaultWikitextNS() {
2432 global $wgNamespaceContentModels;
2433
2434 static $wikitextNS = null; // this is not going to change
2435 if ( $wikitextNS !== null ) {
2436 return $wikitextNS;
2437 }
2438
2439 // quickly short out on the most common case:
2440 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2441 return NS_MAIN;
2442 }
2443
2444 // NOTE: prefer content namespaces
2445 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
2446 $namespaces = array_unique( array_merge(
2447 $nsInfo->getContentNamespaces(),
2448 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2449 $nsInfo->getValidNamespaces()
2450 ) );
2451
2452 $namespaces = array_diff( $namespaces, [
2453 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2454 ] );
2455
2456 $talk = array_filter( $namespaces, static function ( $ns ) use ( $nsInfo ) {
2457 return $nsInfo->isTalk( $ns );
2458 } );
2459
2460 // prefer non-talk pages
2461 $namespaces = array_diff( $namespaces, $talk );
2462 $namespaces = array_merge( $namespaces, $talk );
2463
2464 // check the default content model of each namespace
2465 foreach ( $namespaces as $ns ) {
2466 if ( $this->isWikitextNS( $ns ) ) {
2467 $wikitextNS = $ns;
2468 return $wikitextNS;
2469 }
2470 }
2471
2472 // give up
2473 // @todo Inside a test, we could skip the test as incomplete.
2474 // But frequently, this is used in fixture setup.
2475 throw new RuntimeException( "No namespace defaults to wikitext!" );
2476 }
2477
2478 /**
2479 * Check, if $wgDiff3 is set and ready to merge
2480 * Will mark the calling test as skipped, if not ready
2481 *
2482 * @since 1.21
2483 */
2484 protected function markTestSkippedIfNoDiff3() {
2485 global $wgDiff3;
2486
2487 // This check may also protect against code injection in
2488 // case of broken installations.
2489 $haveDiff3 = $wgDiff3 && @is_file( $wgDiff3 );
2490 if ( !$haveDiff3 ) {
2491 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2492 }
2493 }
2494
2495 /**
2496 * Skip the test if using the specified database type
2497 *
2498 * @since 1.32
2499 *
2500 * @param string $type Database type
2501 */
2502 protected function markTestSkippedIfDbType( $type ) {
2503 if ( $this->db->getType() === $type ) {
2504 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2505 }
2506 }
2507
2508 /**
2509 * Skip the test if the specified extension is not loaded.
2510 *
2511 * @note Core tests should not depend on extensions, so this is mostly
2512 * useful when testing extensions that optionally depend on other extensions.
2513 *
2514 * @since 1.37
2515 *
2516 * @param string $extensionName
2517 */
2518 protected function markTestSkippedIfExtensionNotLoaded( string $extensionName ) {
2519 if ( !ExtensionRegistry::getInstance()->isLoaded( $extensionName ) ) {
2520 $this->markTestSkipped( "Extension $extensionName is required for this test" );
2521 }
2522 }
2523
2524 /**
2525 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2526 *
2527 * @param string $buffer
2528 * @return string
2529 */
2530 public static function wfResetOutputBuffersBarrier( $buffer ) {
2531 return $buffer;
2532 }
2533
2534 /**
2535 * Registers the given hook handler for the duration of the current test case.
2536 *
2537 * @param string $hookName
2538 * @param mixed $handler Value suitable for a hook handler
2539 * @param bool $replace (optional) Default is to replace all existing handlers for the given hook.
2540 * Set false to add to the existing handler list.
2541 * @since 1.28
2542 */
2543 protected function setTemporaryHook( $hookName, $handler, $replace = true ) {
2544 if ( $replace ) {
2545 $this->clearHook( $hookName );
2546 }
2547 $this->localServices->getHookContainer()->register( $hookName, $handler );
2548 $this->temporaryHookHandlers[] = [ $hookName, $handler ];
2549 }
2550
2551 /**
2552 * Remove all handlers for the given hook for the duration of the current test case.
2553 *
2554 * @since 1.36
2555 *
2556 * @param string $hookName
2557 */
2558 protected function clearHook( $hookName ) {
2559 $this->localServices->getHookContainer()->clear( $hookName );
2560 $this->temporaryHookHandlers[] = [ $hookName, false ];
2561 }
2562
2563 /**
2564 * Remove all handlers for the given hooks for the duration of the current test case.
2565 * If called without any parameters, this clears all hooks.
2566 *
2567 * @since 1.40
2568 *
2569 * @param string[]|null $hookNames
2570 */
2571 protected function clearHooks( ?array $hookNames = null ) {
2572 $hookNames ??= $this->localServices->getHookContainer()->getHookNames();
2573 foreach ( $hookNames as $name ) {
2574 $this->clearHook( $name );
2575 }
2576 }
2577
2578 /**
2579 * Remove a temporary hook previously added with setTemporaryHook().
2580 *
2581 * @note This is implemented to remove ALL handlers for the given hook
2582 * for the duration of the current test case.
2583 * @deprecated since 1.36, use clearHook() instead.
2584 *
2585 * @param string $hookName
2586 */
2587 protected function removeTemporaryHook( $hookName ) {
2588 $this->clearHook( $hookName );
2589 }
2590
2591 /**
2592 * Edits or creates a page/revision. This method requires database support, which can be enabled with
2593 * "@group Database".
2594 *
2595 * @param string|PageIdentity|LinkTarget|WikiPage $page the page to edit
2596 * @param string|Content $content the new content of the page
2597 * @param string $summary Optional summary string for the revision
2598 * @param int $defaultNs Optional namespace id
2599 * @param Authority|null $performer If null, static::getTestUser()->getAuthority() is used.
2600 * @return PageUpdateStatus Object as returned by WikiPage::doUserEditContent()
2601 */
2602 protected function editPage(
2603 $page,
2604 $content,
2605 $summary = '',
2606 $defaultNs = NS_MAIN,
2607 ?Authority $performer = null
2608 ) {
2609 if ( !self::needsDB() ) {
2610 throw new LogicException( 'When testing with pages, the test must use @group Database.' );
2611 }
2612
2613 $services = $this->getServiceContainer();
2614 if ( $page instanceof WikiPage ) {
2615 $title = $page->getTitle();
2616 } elseif ( $page instanceof PageIdentity ) {
2617 $page = $services->getWikiPageFactory()->newFromTitle( $page );
2618 $title = $page->getTitle();
2619 } elseif ( $page instanceof LinkTarget ) {
2620 $page = $services->getWikiPageFactory()->newFromLinkTarget( $page );
2621 $title = $page->getTitle();
2622 } else {
2623 $title = $services->getTitleFactory()->newFromText( $page, $defaultNs );
2624 $page = $services->getWikiPageFactory()->newFromTitle( $title );
2625 }
2626
2627 if ( is_string( $content ) ) {
2628 $content = $services->getContentHandlerFactory()
2629 ->getContentHandler( $title->getContentModel() )
2630 ->unserializeContent( $content );
2631 }
2632
2633 return $page->doUserEditContent(
2634 $content,
2635 $performer ?? static::getTestUser()->getAuthority(),
2636 $summary
2637 );
2638 }
2639
2640 /**
2641 * @param ProperPageIdentity $page
2642 * @param string $summary
2643 * @param Authority|null $deleter
2644 */
2645 protected function deletePage( ProperPageIdentity $page, string $summary = '', ?Authority $deleter = null ): void {
2646 $deleter ??= new UltimateAuthority( new UserIdentityValue( 0, 'MediaWiki default' ) );
2647 MediaWikiServices::getInstance()->getDeletePageFactory()
2648 ->newDeletePage( $page, $deleter )
2649 ->deleteUnsafe( $summary );
2650 }
2651
2652 /**
2653 * Revision-deletes a revision.
2654 *
2655 * @param RevisionRecord|int $rev Revision to delete
2656 * @param array $value Keys are RevisionRecord::DELETED_* flags. Values are 1 to set the bit,
2657 * 0 to clear, -1 to leave alone. (All other values also clear the bit.)
2658 * @param string $comment Deletion comment
2659 */
2660 protected function revisionDelete(
2661 $rev, array $value = [ RevisionRecord::DELETED_TEXT => 1 ], $comment = ''
2662 ) {
2663 if ( is_int( $rev ) ) {
2664 $rev = MediaWikiServices::getInstance()
2665 ->getRevisionLookup()
2666 ->getRevisionById( $rev );
2667 }
2668
2669 // Make sure the context user is set to a named user account, otherwise
2670 // ::createList will fail when temp accounts are enabled, because
2671 // that generates a log entry which requires a named or temp account actor
2672 RequestContext::getMain()->setUser( $this->getTestUser()->getUser() );
2673 RevisionDeleter::createList(
2674 'revision', RequestContext::getMain(), $rev->getPage(), [ $rev->getId() ]
2675 )->setVisibility( [
2676 'value' => $value,
2677 'comment' => $comment,
2678 ] );
2679 }
2680
2681 /**
2682 * Run jobs in the job queue and assert things about the result.
2683 *
2684 * Call this from a test to run jobs. If this is not called, the default
2685 * behaviour is to discard jobs.
2686 *
2687 * @param array $assertOptions An associative array with the following options:
2688 * - minJobs: The minimum number of jobs expected to be run, default 1
2689 * - numJobs: The exact number of jobs expected to be run. If set, this
2690 * overrides minJobs.
2691 * - complete: Assert that the runner finished with "none-ready", which
2692 * means execution stopped because the queue was empty. Default true.
2693 * - ignoreErrorsMatchingFormat: Allow job errors where the error message
2694 * matches the given format.
2695 * @param array $runOptions Options to pass through to JobRunner::run()
2696 *
2697 * @since 1.37
2698 */
2699 protected function runJobs( array $assertOptions = [], array $runOptions = [] ) {
2700 $runner = $this->getServiceContainer()->getJobRunner();
2701 $status = $runner->run( $runOptions );
2702
2703 $minJobs = $assertOptions['minJobs'] ?? 1;
2704 $numJobs = $assertOptions['numJobs'] ?? null;
2705 $complete = $assertOptions['complete'] ?? true;
2706 $ignoreFormat = $assertOptions['ignoreErrorsMatchingFormat'] ?? false;
2707
2708 if ( $complete ) {
2709 $this->assertSame( 'none-ready', $status['reached'] );
2710 }
2711 if ( $numJobs !== null ) {
2712 $this->assertCount( $numJobs, $status['jobs'],
2713 "Number of jobs executed must be exactly $numJobs" );
2714 } else {
2715 $this->assertGreaterThanOrEqual( $minJobs, count( $status['jobs'] ),
2716 "Number of jobs executed must be at least $minJobs" );
2717 }
2718 foreach ( $status['jobs'] as $jobStatus ) {
2719 if ( $ignoreFormat !== false ) {
2720 $this->assertThat( $jobStatus['error'],
2721 $this->logicalOr(
2722 $this->isNull(),
2723 $this->matches( $ignoreFormat )
2724 ),
2725 "Error for job of type {$jobStatus['type']}"
2726 );
2727 } else {
2728 $this->assertNull( $jobStatus['error'],
2729 "Error for job of type {$jobStatus['type']}" );
2730 }
2731 }
2732 }
2733 }