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