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