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