Update tests/phpunit/MediaWikiTestCase.php with support for apcu
[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_' . get_class( $this ) . '_' );
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 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
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 "
1308 . get_class( $this ) );
1309 }
1310 }
1311
1312 /**
1313 * Used as a compatibility method for phpunit < 3.7.32
1314 * @param string $value
1315 * @param string $msg
1316 */
1317 private function assertEmpty2( $value, $msg ) {
1318 $this->assertTrue( $value == '', $msg );
1319 }
1320
1321 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1322 $tableName = substr( $tableName, strlen( $prefix ) );
1323 }
1324
1325 private static function isNotUnittest( $table ) {
1326 return strpos( $table, 'unittest_' ) !== 0;
1327 }
1328
1329 /**
1330 * @since 1.18
1331 *
1332 * @param IMaintainableDatabase $db
1333 *
1334 * @return array
1335 */
1336 public static function listTables( IMaintainableDatabase $db ) {
1337 $prefix = $db->tablePrefix();
1338 $tables = $db->listTables( $prefix, __METHOD__ );
1339
1340 if ( $db->getType() === 'mysql' ) {
1341 static $viewListCache = null;
1342 if ( $viewListCache === null ) {
1343 $viewListCache = $db->listViews( null, __METHOD__ );
1344 }
1345 // T45571: cannot clone VIEWs under MySQL
1346 $tables = array_diff( $tables, $viewListCache );
1347 }
1348 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1349
1350 // Don't duplicate test tables from the previous fataled run
1351 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1352
1353 if ( $db->getType() == 'sqlite' ) {
1354 $tables = array_flip( $tables );
1355 // these are subtables of searchindex and don't need to be duped/dropped separately
1356 unset( $tables['searchindex_content'] );
1357 unset( $tables['searchindex_segdir'] );
1358 unset( $tables['searchindex_segments'] );
1359 $tables = array_flip( $tables );
1360 }
1361
1362 return $tables;
1363 }
1364
1365 /**
1366 * @throws MWException
1367 * @since 1.18
1368 */
1369 protected function checkDbIsSupported() {
1370 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1371 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1372 }
1373 }
1374
1375 /**
1376 * @since 1.18
1377 * @param string $offset
1378 * @return mixed
1379 */
1380 public function getCliArg( $offset ) {
1381 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1382 return PHPUnitMaintClass::$additionalOptions[$offset];
1383 }
1384
1385 return null;
1386 }
1387
1388 /**
1389 * @since 1.18
1390 * @param string $offset
1391 * @param mixed $value
1392 */
1393 public function setCliArg( $offset, $value ) {
1394 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1395 }
1396
1397 /**
1398 * Don't throw a warning if $function is deprecated and called later
1399 *
1400 * @since 1.19
1401 *
1402 * @param string $function
1403 */
1404 public function hideDeprecated( $function ) {
1405 MediaWiki\suppressWarnings();
1406 wfDeprecated( $function );
1407 MediaWiki\restoreWarnings();
1408 }
1409
1410 /**
1411 * Asserts that the given database query yields the rows given by $expectedRows.
1412 * The expected rows should be given as indexed (not associative) arrays, with
1413 * the values given in the order of the columns in the $fields parameter.
1414 * Note that the rows are sorted by the columns given in $fields.
1415 *
1416 * @since 1.20
1417 *
1418 * @param string|array $table The table(s) to query
1419 * @param string|array $fields The columns to include in the result (and to sort by)
1420 * @param string|array $condition "where" condition(s)
1421 * @param array $expectedRows An array of arrays giving the expected rows.
1422 *
1423 * @throws MWException If this test cases's needsDB() method doesn't return true.
1424 * Test cases can use "@group Database" to enable database test support,
1425 * or list the tables under testing in $this->tablesUsed, or override the
1426 * needsDB() method.
1427 */
1428 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1429 if ( !$this->needsDB() ) {
1430 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1431 ' method should return true. Use @group Database or $this->tablesUsed.' );
1432 }
1433
1434 $db = wfGetDB( DB_SLAVE );
1435
1436 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1437 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1438
1439 $i = 0;
1440
1441 foreach ( $expectedRows as $expected ) {
1442 $r = $res->fetchRow();
1443 self::stripStringKeys( $r );
1444
1445 $i += 1;
1446 $this->assertNotEmpty( $r, "row #$i missing" );
1447
1448 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1449 }
1450
1451 $r = $res->fetchRow();
1452 self::stripStringKeys( $r );
1453
1454 $this->assertFalse( $r, "found extra row (after #$i)" );
1455 }
1456
1457 /**
1458 * Utility method taking an array of elements and wrapping
1459 * each element in its own array. Useful for data providers
1460 * that only return a single argument.
1461 *
1462 * @since 1.20
1463 *
1464 * @param array $elements
1465 *
1466 * @return array
1467 */
1468 protected function arrayWrap( array $elements ) {
1469 return array_map(
1470 function ( $element ) {
1471 return [ $element ];
1472 },
1473 $elements
1474 );
1475 }
1476
1477 /**
1478 * Assert that two arrays are equal. By default this means that both arrays need to hold
1479 * the same set of values. Using additional arguments, order and associated key can also
1480 * be set as relevant.
1481 *
1482 * @since 1.20
1483 *
1484 * @param array $expected
1485 * @param array $actual
1486 * @param bool $ordered If the order of the values should match
1487 * @param bool $named If the keys should match
1488 */
1489 protected function assertArrayEquals( array $expected, array $actual,
1490 $ordered = false, $named = false
1491 ) {
1492 if ( !$ordered ) {
1493 $this->objectAssociativeSort( $expected );
1494 $this->objectAssociativeSort( $actual );
1495 }
1496
1497 if ( !$named ) {
1498 $expected = array_values( $expected );
1499 $actual = array_values( $actual );
1500 }
1501
1502 call_user_func_array(
1503 [ $this, 'assertEquals' ],
1504 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1505 );
1506 }
1507
1508 /**
1509 * Put each HTML element on its own line and then equals() the results
1510 *
1511 * Use for nicely formatting of PHPUnit diff output when comparing very
1512 * simple HTML
1513 *
1514 * @since 1.20
1515 *
1516 * @param string $expected HTML on oneline
1517 * @param string $actual HTML on oneline
1518 * @param string $msg Optional message
1519 */
1520 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1521 $expected = str_replace( '>', ">\n", $expected );
1522 $actual = str_replace( '>', ">\n", $actual );
1523
1524 $this->assertEquals( $expected, $actual, $msg );
1525 }
1526
1527 /**
1528 * Does an associative sort that works for objects.
1529 *
1530 * @since 1.20
1531 *
1532 * @param array $array
1533 */
1534 protected function objectAssociativeSort( array &$array ) {
1535 uasort(
1536 $array,
1537 function ( $a, $b ) {
1538 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1539 }
1540 );
1541 }
1542
1543 /**
1544 * Utility function for eliminating all string keys from an array.
1545 * Useful to turn a database result row as returned by fetchRow() into
1546 * a pure indexed array.
1547 *
1548 * @since 1.20
1549 *
1550 * @param mixed $r The array to remove string keys from.
1551 */
1552 protected static function stripStringKeys( &$r ) {
1553 if ( !is_array( $r ) ) {
1554 return;
1555 }
1556
1557 foreach ( $r as $k => $v ) {
1558 if ( is_string( $k ) ) {
1559 unset( $r[$k] );
1560 }
1561 }
1562 }
1563
1564 /**
1565 * Asserts that the provided variable is of the specified
1566 * internal type or equals the $value argument. This is useful
1567 * for testing return types of functions that return a certain
1568 * type or *value* when not set or on error.
1569 *
1570 * @since 1.20
1571 *
1572 * @param string $type
1573 * @param mixed $actual
1574 * @param mixed $value
1575 * @param string $message
1576 */
1577 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1578 if ( $actual === $value ) {
1579 $this->assertTrue( true, $message );
1580 } else {
1581 $this->assertType( $type, $actual, $message );
1582 }
1583 }
1584
1585 /**
1586 * Asserts the type of the provided value. This can be either
1587 * in internal type such as boolean or integer, or a class or
1588 * interface the value extends or implements.
1589 *
1590 * @since 1.20
1591 *
1592 * @param string $type
1593 * @param mixed $actual
1594 * @param string $message
1595 */
1596 protected function assertType( $type, $actual, $message = '' ) {
1597 if ( class_exists( $type ) || interface_exists( $type ) ) {
1598 $this->assertInstanceOf( $type, $actual, $message );
1599 } else {
1600 $this->assertInternalType( $type, $actual, $message );
1601 }
1602 }
1603
1604 /**
1605 * Returns true if the given namespace defaults to Wikitext
1606 * according to $wgNamespaceContentModels
1607 *
1608 * @param int $ns The namespace ID to check
1609 *
1610 * @return bool
1611 * @since 1.21
1612 */
1613 protected function isWikitextNS( $ns ) {
1614 global $wgNamespaceContentModels;
1615
1616 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1617 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1618 }
1619
1620 return true;
1621 }
1622
1623 /**
1624 * Returns the ID of a namespace that defaults to Wikitext.
1625 *
1626 * @throws MWException If there is none.
1627 * @return int The ID of the wikitext Namespace
1628 * @since 1.21
1629 */
1630 protected function getDefaultWikitextNS() {
1631 global $wgNamespaceContentModels;
1632
1633 static $wikitextNS = null; // this is not going to change
1634 if ( $wikitextNS !== null ) {
1635 return $wikitextNS;
1636 }
1637
1638 // quickly short out on most common case:
1639 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1640 return NS_MAIN;
1641 }
1642
1643 // NOTE: prefer content namespaces
1644 $namespaces = array_unique( array_merge(
1645 MWNamespace::getContentNamespaces(),
1646 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1647 MWNamespace::getValidNamespaces()
1648 ) );
1649
1650 $namespaces = array_diff( $namespaces, [
1651 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1652 ] );
1653
1654 $talk = array_filter( $namespaces, function ( $ns ) {
1655 return MWNamespace::isTalk( $ns );
1656 } );
1657
1658 // prefer non-talk pages
1659 $namespaces = array_diff( $namespaces, $talk );
1660 $namespaces = array_merge( $namespaces, $talk );
1661
1662 // check default content model of each namespace
1663 foreach ( $namespaces as $ns ) {
1664 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1665 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1666 ) {
1667
1668 $wikitextNS = $ns;
1669
1670 return $wikitextNS;
1671 }
1672 }
1673
1674 // give up
1675 // @todo Inside a test, we could skip the test as incomplete.
1676 // But frequently, this is used in fixture setup.
1677 throw new MWException( "No namespace defaults to wikitext!" );
1678 }
1679
1680 /**
1681 * Check, if $wgDiff3 is set and ready to merge
1682 * Will mark the calling test as skipped, if not ready
1683 *
1684 * @since 1.21
1685 */
1686 protected function markTestSkippedIfNoDiff3() {
1687 global $wgDiff3;
1688
1689 # This check may also protect against code injection in
1690 # case of broken installations.
1691 MediaWiki\suppressWarnings();
1692 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1693 MediaWiki\restoreWarnings();
1694
1695 if ( !$haveDiff3 ) {
1696 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1697 }
1698 }
1699
1700 /**
1701 * Check if $extName is a loaded PHP extension, will skip the
1702 * test whenever it is not loaded.
1703 *
1704 * @since 1.21
1705 * @param string $extName
1706 * @return bool
1707 */
1708 protected function checkPHPExtension( $extName ) {
1709 $loaded = extension_loaded( $extName );
1710 if ( !$loaded ) {
1711 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1712 }
1713
1714 return $loaded;
1715 }
1716
1717 /**
1718 * Asserts that the given string is a valid HTML snippet.
1719 * Wraps the given string in the required top level tags and
1720 * then calls assertValidHtmlDocument().
1721 * The snippet is expected to be HTML 5.
1722 *
1723 * @since 1.23
1724 *
1725 * @note Will mark the test as skipped if the "tidy" module is not installed.
1726 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1727 * when automatic tidying is disabled.
1728 *
1729 * @param string $html An HTML snippet (treated as the contents of the body tag).
1730 */
1731 protected function assertValidHtmlSnippet( $html ) {
1732 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1733 $this->assertValidHtmlDocument( $html );
1734 }
1735
1736 /**
1737 * Asserts that the given string is valid HTML document.
1738 *
1739 * @since 1.23
1740 *
1741 * @note Will mark the test as skipped if the "tidy" module is not installed.
1742 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1743 * when automatic tidying is disabled.
1744 *
1745 * @param string $html A complete HTML document
1746 */
1747 protected function assertValidHtmlDocument( $html ) {
1748 // Note: we only validate if the tidy PHP extension is available.
1749 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1750 // of tidy. In that case however, we can not reliably detect whether a failing validation
1751 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1752 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1753 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1754 $this->markTestSkipped( 'Tidy extension not installed' );
1755 }
1756
1757 $errorBuffer = '';
1758 MWTidy::checkErrors( $html, $errorBuffer );
1759 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1760
1761 // Filter Tidy warnings which aren't useful for us.
1762 // Tidy eg. often cries about parameters missing which have actually
1763 // been deprecated since HTML4, thus we should not care about them.
1764 $errors = preg_grep(
1765 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1766 $allErrors, PREG_GREP_INVERT
1767 );
1768
1769 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1770 }
1771
1772 /**
1773 * @param array $matcher
1774 * @param string $actual
1775 * @param bool $isHtml
1776 *
1777 * @return bool
1778 */
1779 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1780 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1781 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1782 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1783 }
1784
1785 /**
1786 * Note: we are overriding this method to remove the deprecated error
1787 * @see https://phabricator.wikimedia.org/T71505
1788 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1789 * @deprecated
1790 *
1791 * @param array $matcher
1792 * @param string $actual
1793 * @param string $message
1794 * @param bool $isHtml
1795 */
1796 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1797 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1798
1799 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1800 }
1801
1802 /**
1803 * @see MediaWikiTestCase::assertTag
1804 * @deprecated
1805 *
1806 * @param array $matcher
1807 * @param string $actual
1808 * @param string $message
1809 * @param bool $isHtml
1810 */
1811 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1812 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1813
1814 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1815 }
1816
1817 /**
1818 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1819 * @return string
1820 */
1821 public static function wfResetOutputBuffersBarrier( $buffer ) {
1822 return $buffer;
1823 }
1824
1825 /**
1826 * Create a temporary hook handler which will be reset by tearDown.
1827 * This replaces other handlers for the same hook.
1828 * @param string $hookName Hook name
1829 * @param mixed $handler Value suitable for a hook handler
1830 * @since 1.28
1831 */
1832 protected function setTemporaryHook( $hookName, $handler ) {
1833 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
1834 }
1835
1836 }