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