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