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