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