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