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