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