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