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