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