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