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