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