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