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