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