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