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