Merge "Use classes to apply the 'editfont' preference"
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2 use MediaWiki\Logger\LegacySpi;
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\MonologSpi;
5 use MediaWiki\MediaWikiServices;
6 use Psr\Log\LoggerInterface;
7
8 /**
9 * @since 1.18
10 */
11 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
12
13 /**
14 * The service locator created by prepareServices(). This service locator will
15 * be restored after each test. Tests that pollute the global service locator
16 * instance should use overrideMwServices() to isolate the test.
17 *
18 * @var MediaWikiServices|null
19 */
20 private static $serviceLocator = null;
21
22 /**
23 * $called tracks whether the setUp and tearDown method has been called.
24 * class extending MediaWikiTestCase usually override setUp and tearDown
25 * but forget to call the parent.
26 *
27 * The array format takes a method name as key and anything as a value.
28 * By asserting the key exist, we know the child class has called the
29 * parent.
30 *
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
33 */
34 private $called = [];
35
36 /**
37 * @var TestUser[]
38 * @since 1.20
39 */
40 public static $users;
41
42 /**
43 * Primary database
44 *
45 * @var Database
46 * @since 1.18
47 */
48 protected $db;
49
50 /**
51 * @var array
52 * @since 1.19
53 */
54 protected $tablesUsed = []; // tables with data
55
56 private static $useTemporaryTables = true;
57 private static $reuseDB = false;
58 private static $dbSetup = false;
59 private static $oldTablePrefix = '';
60
61 /**
62 * Original value of PHP's error_reporting setting.
63 *
64 * @var int
65 */
66 private $phpErrorLevel;
67
68 /**
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
71 *
72 * @var array
73 */
74 private $tmpFiles = [];
75
76 /**
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
80 * @var array
81 */
82 private $mwGlobals = [];
83
84 /**
85 * Holds 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 ($namespace in 1.28)
924 * @param string|title $pageName Page name or title
925 * @param string $text Page's content
926 * @param int $namespace Namespace id (name cannot already contain namespace)
927 * @return array Title object and page id
928 */
929 protected function insertPage(
930 $pageName,
931 $text = 'Sample page for unit test.',
932 $namespace = null
933 ) {
934 if ( is_string( $pageName ) ) {
935 $title = Title::newFromText( $pageName, $namespace );
936 } else {
937 $title = $pageName;
938 }
939
940 $user = static::getTestSysop()->getUser();
941 $comment = __METHOD__ . ': Sample page for unit test.';
942
943 // Avoid memory leak...?
944 // LinkCache::singleton()->clear();
945 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
946
947 $page = WikiPage::factory( $title );
948 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
949
950 return [
951 'title' => $title,
952 'id' => $page->getId(),
953 ];
954 }
955
956 /**
957 * Stub. If a test suite needs to add additional data to the database, it should
958 * implement this method and do so. This method is called once per test suite
959 * (i.e. once per class).
960 *
961 * Note data added by this method may be removed by resetDB() depending on
962 * the contents of $tablesUsed.
963 *
964 * To add additional data between test function runs, override prepareDB().
965 *
966 * @see addDBData()
967 * @see resetDB()
968 *
969 * @since 1.27
970 */
971 public function addDBDataOnce() {
972 }
973
974 /**
975 * Stub. Subclasses may override this to prepare the database.
976 * Called before every test run (test function or data set).
977 *
978 * @see addDBDataOnce()
979 * @see resetDB()
980 *
981 * @since 1.18
982 */
983 public function addDBData() {
984 }
985
986 private function addCoreDBData() {
987 if ( $this->db->getType() == 'oracle' ) {
988
989 # Insert 0 user to prevent FK violations
990 # Anonymous user
991 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
992 $this->db->insert( 'user', [
993 'user_id' => 0,
994 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
995 }
996
997 # Insert 0 page to prevent FK violations
998 # Blank page
999 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1000 $this->db->insert( 'page', [
1001 'page_id' => 0,
1002 'page_namespace' => 0,
1003 'page_title' => ' ',
1004 'page_restrictions' => null,
1005 'page_is_redirect' => 0,
1006 'page_is_new' => 0,
1007 'page_random' => 0,
1008 'page_touched' => $this->db->timestamp(),
1009 'page_latest' => 0,
1010 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1011 }
1012 }
1013
1014 User::resetIdByNameCache();
1015
1016 // Make sysop user
1017 $user = static::getTestSysop()->getUser();
1018
1019 // Make 1 page with 1 revision
1020 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1021 if ( $page->getId() == 0 ) {
1022 $page->doEditContent(
1023 new WikitextContent( 'UTContent' ),
1024 'UTPageSummary',
1025 EDIT_NEW,
1026 false,
1027 $user
1028 );
1029
1030 // doEditContent() probably started the session via
1031 // User::loadFromSession(). Close it now.
1032 if ( session_id() !== '' ) {
1033 session_write_close();
1034 session_id( '' );
1035 }
1036 }
1037 }
1038
1039 /**
1040 * Restores MediaWiki to using the table set (table prefix) it was using before
1041 * setupTestDB() was called. Useful if we need to perform database operations
1042 * after the test run has finished (such as saving logs or profiling info).
1043 *
1044 * @since 1.21
1045 */
1046 public static function teardownTestDB() {
1047 global $wgJobClasses;
1048
1049 if ( !self::$dbSetup ) {
1050 return;
1051 }
1052
1053 foreach ( $wgJobClasses as $type => $class ) {
1054 // Delete any jobs under the clone DB (or old prefix in other stores)
1055 JobQueueGroup::singleton()->get( $type )->delete();
1056 }
1057
1058 CloneDatabase::changePrefix( self::$oldTablePrefix );
1059
1060 self::$oldTablePrefix = false;
1061 self::$dbSetup = false;
1062 }
1063
1064 /**
1065 * Setups a database with the given prefix.
1066 *
1067 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1068 * Otherwise, it will clone the tables and change the prefix.
1069 *
1070 * Clones all tables in the given database (whatever database that connection has
1071 * open), to versions with the test prefix.
1072 *
1073 * @param Database $db Database to use
1074 * @param string $prefix Prefix to use for test tables
1075 * @return bool True if tables were cloned, false if only the prefix was changed
1076 */
1077 protected static function setupDatabaseWithTestPrefix( Database $db, $prefix ) {
1078 $tablesCloned = self::listTables( $db );
1079 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1080 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1081
1082 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1083 CloneDatabase::changePrefix( $prefix );
1084
1085 return false;
1086 } else {
1087 $dbClone->cloneTableStructure();
1088 return true;
1089 }
1090 }
1091
1092 /**
1093 * Set up all test DBs
1094 */
1095 public function setupAllTestDBs() {
1096 global $wgDBprefix;
1097
1098 self::$oldTablePrefix = $wgDBprefix;
1099
1100 $testPrefix = $this->dbPrefix();
1101
1102 // switch to a temporary clone of the database
1103 self::setupTestDB( $this->db, $testPrefix );
1104
1105 if ( self::isUsingExternalStoreDB() ) {
1106 self::setupExternalStoreTestDBs( $testPrefix );
1107 }
1108 }
1109
1110 /**
1111 * Creates an empty skeleton of the wiki database by cloning its structure
1112 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1113 * use the new set of tables (aka schema) instead of the original set.
1114 *
1115 * This is used to generate a dummy table set, typically consisting of temporary
1116 * tables, that will be used by tests instead of the original wiki database tables.
1117 *
1118 * @since 1.21
1119 *
1120 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1121 * by teardownTestDB() to return the wiki to using the original table set.
1122 *
1123 * @note this method only works when first called. Subsequent calls have no effect,
1124 * even if using different parameters.
1125 *
1126 * @param Database $db The database connection
1127 * @param string $prefix The prefix to use for the new table set (aka schema).
1128 *
1129 * @throws MWException If the database table prefix is already $prefix
1130 */
1131 public static function setupTestDB( Database $db, $prefix ) {
1132 if ( self::$dbSetup ) {
1133 return;
1134 }
1135
1136 if ( $db->tablePrefix() === $prefix ) {
1137 throw new MWException(
1138 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1139 }
1140
1141 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1142 // and Database no longer use global state.
1143
1144 self::$dbSetup = true;
1145
1146 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1147 return;
1148 }
1149
1150 // Assuming this isn't needed for External Store database, and not sure if the procedure
1151 // would be available there.
1152 if ( $db->getType() == 'oracle' ) {
1153 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1154 }
1155 }
1156
1157 /**
1158 * Clones the External Store database(s) for testing
1159 *
1160 * @param string $testPrefix Prefix for test tables
1161 */
1162 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1163 $connections = self::getExternalStoreDatabaseConnections();
1164 foreach ( $connections as $dbw ) {
1165 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1166 // prefix,. Even though listTables now uses tablePrefix, that
1167 // itself is populated from $wgDBprefix by default.
1168
1169 // We have to set it back, or we won't find the original 'blobs'
1170 // table to copy.
1171
1172 $dbw->tablePrefix( self::$oldTablePrefix );
1173 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1174 }
1175 }
1176
1177 /**
1178 * Gets master database connections for all of the ExternalStoreDB
1179 * stores configured in $wgDefaultExternalStore.
1180 *
1181 * @return Database[] Array of Database master connections
1182 */
1183
1184 protected static function getExternalStoreDatabaseConnections() {
1185 global $wgDefaultExternalStore;
1186
1187 /** @var ExternalStoreDB $externalStoreDB */
1188 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1189 $defaultArray = (array) $wgDefaultExternalStore;
1190 $dbws = [];
1191 foreach ( $defaultArray as $url ) {
1192 if ( strpos( $url, 'DB://' ) === 0 ) {
1193 list( $proto, $cluster ) = explode( '://', $url, 2 );
1194 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1195 // requires Database instead of plain DBConnRef/IDatabase
1196 $lb = $externalStoreDB->getLoadBalancer( $cluster );
1197 $dbw = $lb->getConnection( DB_MASTER );
1198 $dbws[] = $dbw;
1199 }
1200 }
1201
1202 return $dbws;
1203 }
1204
1205 /**
1206 * Check whether ExternalStoreDB is being used
1207 *
1208 * @return bool True if it's being used
1209 */
1210 protected static function isUsingExternalStoreDB() {
1211 global $wgDefaultExternalStore;
1212 if ( !$wgDefaultExternalStore ) {
1213 return false;
1214 }
1215
1216 $defaultArray = (array) $wgDefaultExternalStore;
1217 foreach ( $defaultArray as $url ) {
1218 if ( strpos( $url, 'DB://' ) === 0 ) {
1219 return true;
1220 }
1221 }
1222
1223 return false;
1224 }
1225
1226 /**
1227 * Empty all tables so they can be repopulated for tests
1228 *
1229 * @param Database $db|null Database to reset
1230 * @param array $tablesUsed Tables to reset
1231 */
1232 private function resetDB( $db, $tablesUsed ) {
1233 if ( $db ) {
1234 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1235 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1236
1237 // If any of the user tables were marked as used, we should clear all of them.
1238 if ( array_intersect( $tablesUsed, $userTables ) ) {
1239 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1240 TestUserRegistry::clear();
1241 }
1242
1243 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1244 foreach ( $tablesUsed as $tbl ) {
1245 // TODO: reset interwiki table to its original content.
1246 if ( $tbl == 'interwiki' ) {
1247 continue;
1248 }
1249
1250 if ( $truncate ) {
1251 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1252 } else {
1253 $db->delete( $tbl, '*', __METHOD__ );
1254 }
1255
1256 if ( $tbl === 'page' ) {
1257 // Forget about the pages since they don't
1258 // exist in the DB.
1259 LinkCache::singleton()->clear();
1260 }
1261 }
1262
1263 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1264 // Re-add core DB data that was deleted
1265 $this->addCoreDBData();
1266 }
1267 }
1268 }
1269
1270 /**
1271 * @since 1.18
1272 *
1273 * @param string $func
1274 * @param array $args
1275 *
1276 * @return mixed
1277 * @throws MWException
1278 */
1279 public function __call( $func, $args ) {
1280 static $compatibility = [
1281 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1282 ];
1283
1284 if ( isset( $compatibility[$func] ) ) {
1285 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1286 } else {
1287 throw new MWException( "Called non-existent $func method on "
1288 . get_class( $this ) );
1289 }
1290 }
1291
1292 /**
1293 * Used as a compatibility method for phpunit < 3.7.32
1294 * @param string $value
1295 * @param string $msg
1296 */
1297 private function assertEmpty2( $value, $msg ) {
1298 $this->assertTrue( $value == '', $msg );
1299 }
1300
1301 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1302 $tableName = substr( $tableName, strlen( $prefix ) );
1303 }
1304
1305 private static function isNotUnittest( $table ) {
1306 return strpos( $table, 'unittest_' ) !== 0;
1307 }
1308
1309 /**
1310 * @since 1.18
1311 *
1312 * @param Database $db
1313 *
1314 * @return array
1315 */
1316 public static function listTables( Database $db ) {
1317 $prefix = $db->tablePrefix();
1318 $tables = $db->listTables( $prefix, __METHOD__ );
1319
1320 if ( $db->getType() === 'mysql' ) {
1321 static $viewListCache = null;
1322 if ( $viewListCache === null ) {
1323 $viewListCache = $db->listViews( null, __METHOD__ );
1324 }
1325 // T45571: cannot clone VIEWs under MySQL
1326 $tables = array_diff( $tables, $viewListCache );
1327 }
1328 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1329
1330 // Don't duplicate test tables from the previous fataled run
1331 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1332
1333 if ( $db->getType() == 'sqlite' ) {
1334 $tables = array_flip( $tables );
1335 // these are subtables of searchindex and don't need to be duped/dropped separately
1336 unset( $tables['searchindex_content'] );
1337 unset( $tables['searchindex_segdir'] );
1338 unset( $tables['searchindex_segments'] );
1339 $tables = array_flip( $tables );
1340 }
1341
1342 return $tables;
1343 }
1344
1345 /**
1346 * @throws MWException
1347 * @since 1.18
1348 */
1349 protected function checkDbIsSupported() {
1350 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1351 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1352 }
1353 }
1354
1355 /**
1356 * @since 1.18
1357 * @param string $offset
1358 * @return mixed
1359 */
1360 public function getCliArg( $offset ) {
1361 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1362 return PHPUnitMaintClass::$additionalOptions[$offset];
1363 }
1364 }
1365
1366 /**
1367 * @since 1.18
1368 * @param string $offset
1369 * @param mixed $value
1370 */
1371 public function setCliArg( $offset, $value ) {
1372 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1373 }
1374
1375 /**
1376 * Don't throw a warning if $function is deprecated and called later
1377 *
1378 * @since 1.19
1379 *
1380 * @param string $function
1381 */
1382 public function hideDeprecated( $function ) {
1383 MediaWiki\suppressWarnings();
1384 wfDeprecated( $function );
1385 MediaWiki\restoreWarnings();
1386 }
1387
1388 /**
1389 * Asserts that the given database query yields the rows given by $expectedRows.
1390 * The expected rows should be given as indexed (not associative) arrays, with
1391 * the values given in the order of the columns in the $fields parameter.
1392 * Note that the rows are sorted by the columns given in $fields.
1393 *
1394 * @since 1.20
1395 *
1396 * @param string|array $table The table(s) to query
1397 * @param string|array $fields The columns to include in the result (and to sort by)
1398 * @param string|array $condition "where" condition(s)
1399 * @param array $expectedRows An array of arrays giving the expected rows.
1400 *
1401 * @throws MWException If this test cases's needsDB() method doesn't return true.
1402 * Test cases can use "@group Database" to enable database test support,
1403 * or list the tables under testing in $this->tablesUsed, or override the
1404 * needsDB() method.
1405 */
1406 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1407 if ( !$this->needsDB() ) {
1408 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1409 ' method should return true. Use @group Database or $this->tablesUsed.' );
1410 }
1411
1412 $db = wfGetDB( DB_SLAVE );
1413
1414 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1415 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1416
1417 $i = 0;
1418
1419 foreach ( $expectedRows as $expected ) {
1420 $r = $res->fetchRow();
1421 self::stripStringKeys( $r );
1422
1423 $i += 1;
1424 $this->assertNotEmpty( $r, "row #$i missing" );
1425
1426 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1427 }
1428
1429 $r = $res->fetchRow();
1430 self::stripStringKeys( $r );
1431
1432 $this->assertFalse( $r, "found extra row (after #$i)" );
1433 }
1434
1435 /**
1436 * Utility method taking an array of elements and wrapping
1437 * each element in its own array. Useful for data providers
1438 * that only return a single argument.
1439 *
1440 * @since 1.20
1441 *
1442 * @param array $elements
1443 *
1444 * @return array
1445 */
1446 protected function arrayWrap( array $elements ) {
1447 return array_map(
1448 function ( $element ) {
1449 return [ $element ];
1450 },
1451 $elements
1452 );
1453 }
1454
1455 /**
1456 * Assert that two arrays are equal. By default this means that both arrays need to hold
1457 * the same set of values. Using additional arguments, order and associated key can also
1458 * be set as relevant.
1459 *
1460 * @since 1.20
1461 *
1462 * @param array $expected
1463 * @param array $actual
1464 * @param bool $ordered If the order of the values should match
1465 * @param bool $named If the keys should match
1466 */
1467 protected function assertArrayEquals( array $expected, array $actual,
1468 $ordered = false, $named = false
1469 ) {
1470 if ( !$ordered ) {
1471 $this->objectAssociativeSort( $expected );
1472 $this->objectAssociativeSort( $actual );
1473 }
1474
1475 if ( !$named ) {
1476 $expected = array_values( $expected );
1477 $actual = array_values( $actual );
1478 }
1479
1480 call_user_func_array(
1481 [ $this, 'assertEquals' ],
1482 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1483 );
1484 }
1485
1486 /**
1487 * Put each HTML element on its own line and then equals() the results
1488 *
1489 * Use for nicely formatting of PHPUnit diff output when comparing very
1490 * simple HTML
1491 *
1492 * @since 1.20
1493 *
1494 * @param string $expected HTML on oneline
1495 * @param string $actual HTML on oneline
1496 * @param string $msg Optional message
1497 */
1498 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1499 $expected = str_replace( '>', ">\n", $expected );
1500 $actual = str_replace( '>', ">\n", $actual );
1501
1502 $this->assertEquals( $expected, $actual, $msg );
1503 }
1504
1505 /**
1506 * Does an associative sort that works for objects.
1507 *
1508 * @since 1.20
1509 *
1510 * @param array $array
1511 */
1512 protected function objectAssociativeSort( array &$array ) {
1513 uasort(
1514 $array,
1515 function ( $a, $b ) {
1516 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1517 }
1518 );
1519 }
1520
1521 /**
1522 * Utility function for eliminating all string keys from an array.
1523 * Useful to turn a database result row as returned by fetchRow() into
1524 * a pure indexed array.
1525 *
1526 * @since 1.20
1527 *
1528 * @param mixed $r The array to remove string keys from.
1529 */
1530 protected static function stripStringKeys( &$r ) {
1531 if ( !is_array( $r ) ) {
1532 return;
1533 }
1534
1535 foreach ( $r as $k => $v ) {
1536 if ( is_string( $k ) ) {
1537 unset( $r[$k] );
1538 }
1539 }
1540 }
1541
1542 /**
1543 * Asserts that the provided variable is of the specified
1544 * internal type or equals the $value argument. This is useful
1545 * for testing return types of functions that return a certain
1546 * type or *value* when not set or on error.
1547 *
1548 * @since 1.20
1549 *
1550 * @param string $type
1551 * @param mixed $actual
1552 * @param mixed $value
1553 * @param string $message
1554 */
1555 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1556 if ( $actual === $value ) {
1557 $this->assertTrue( true, $message );
1558 } else {
1559 $this->assertType( $type, $actual, $message );
1560 }
1561 }
1562
1563 /**
1564 * Asserts the type of the provided value. This can be either
1565 * in internal type such as boolean or integer, or a class or
1566 * interface the value extends or implements.
1567 *
1568 * @since 1.20
1569 *
1570 * @param string $type
1571 * @param mixed $actual
1572 * @param string $message
1573 */
1574 protected function assertType( $type, $actual, $message = '' ) {
1575 if ( class_exists( $type ) || interface_exists( $type ) ) {
1576 $this->assertInstanceOf( $type, $actual, $message );
1577 } else {
1578 $this->assertInternalType( $type, $actual, $message );
1579 }
1580 }
1581
1582 /**
1583 * Returns true if the given namespace defaults to Wikitext
1584 * according to $wgNamespaceContentModels
1585 *
1586 * @param int $ns The namespace ID to check
1587 *
1588 * @return bool
1589 * @since 1.21
1590 */
1591 protected function isWikitextNS( $ns ) {
1592 global $wgNamespaceContentModels;
1593
1594 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1595 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1596 }
1597
1598 return true;
1599 }
1600
1601 /**
1602 * Returns the ID of a namespace that defaults to Wikitext.
1603 *
1604 * @throws MWException If there is none.
1605 * @return int The ID of the wikitext Namespace
1606 * @since 1.21
1607 */
1608 protected function getDefaultWikitextNS() {
1609 global $wgNamespaceContentModels;
1610
1611 static $wikitextNS = null; // this is not going to change
1612 if ( $wikitextNS !== null ) {
1613 return $wikitextNS;
1614 }
1615
1616 // quickly short out on most common case:
1617 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1618 return NS_MAIN;
1619 }
1620
1621 // NOTE: prefer content namespaces
1622 $namespaces = array_unique( array_merge(
1623 MWNamespace::getContentNamespaces(),
1624 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1625 MWNamespace::getValidNamespaces()
1626 ) );
1627
1628 $namespaces = array_diff( $namespaces, [
1629 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1630 ] );
1631
1632 $talk = array_filter( $namespaces, function ( $ns ) {
1633 return MWNamespace::isTalk( $ns );
1634 } );
1635
1636 // prefer non-talk pages
1637 $namespaces = array_diff( $namespaces, $talk );
1638 $namespaces = array_merge( $namespaces, $talk );
1639
1640 // check default content model of each namespace
1641 foreach ( $namespaces as $ns ) {
1642 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1643 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1644 ) {
1645
1646 $wikitextNS = $ns;
1647
1648 return $wikitextNS;
1649 }
1650 }
1651
1652 // give up
1653 // @todo Inside a test, we could skip the test as incomplete.
1654 // But frequently, this is used in fixture setup.
1655 throw new MWException( "No namespace defaults to wikitext!" );
1656 }
1657
1658 /**
1659 * Check, if $wgDiff3 is set and ready to merge
1660 * Will mark the calling test as skipped, if not ready
1661 *
1662 * @since 1.21
1663 */
1664 protected function markTestSkippedIfNoDiff3() {
1665 global $wgDiff3;
1666
1667 # This check may also protect against code injection in
1668 # case of broken installations.
1669 MediaWiki\suppressWarnings();
1670 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1671 MediaWiki\restoreWarnings();
1672
1673 if ( !$haveDiff3 ) {
1674 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1675 }
1676 }
1677
1678 /**
1679 * Check if $extName is a loaded PHP extension, will skip the
1680 * test whenever it is not loaded.
1681 *
1682 * @since 1.21
1683 * @param string $extName
1684 * @return bool
1685 */
1686 protected function checkPHPExtension( $extName ) {
1687 $loaded = extension_loaded( $extName );
1688 if ( !$loaded ) {
1689 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1690 }
1691
1692 return $loaded;
1693 }
1694
1695 /**
1696 * Asserts that the given string is a valid HTML snippet.
1697 * Wraps the given string in the required top level tags and
1698 * then calls assertValidHtmlDocument().
1699 * The snippet is expected to be HTML 5.
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 An HTML snippet (treated as the contents of the body tag).
1708 */
1709 protected function assertValidHtmlSnippet( $html ) {
1710 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1711 $this->assertValidHtmlDocument( $html );
1712 }
1713
1714 /**
1715 * Asserts that the given string is valid HTML document.
1716 *
1717 * @since 1.23
1718 *
1719 * @note Will mark the test as skipped if the "tidy" module is not installed.
1720 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1721 * when automatic tidying is disabled.
1722 *
1723 * @param string $html A complete HTML document
1724 */
1725 protected function assertValidHtmlDocument( $html ) {
1726 // Note: we only validate if the tidy PHP extension is available.
1727 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1728 // of tidy. In that case however, we can not reliably detect whether a failing validation
1729 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1730 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1731 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1732 $this->markTestSkipped( 'Tidy extension not installed' );
1733 }
1734
1735 $errorBuffer = '';
1736 MWTidy::checkErrors( $html, $errorBuffer );
1737 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1738
1739 // Filter Tidy warnings which aren't useful for us.
1740 // Tidy eg. often cries about parameters missing which have actually
1741 // been deprecated since HTML4, thus we should not care about them.
1742 $errors = preg_grep(
1743 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1744 $allErrors, PREG_GREP_INVERT
1745 );
1746
1747 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1748 }
1749
1750 /**
1751 * @param array $matcher
1752 * @param string $actual
1753 * @param bool $isHtml
1754 *
1755 * @return bool
1756 */
1757 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1758 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1759 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1760 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1761 }
1762
1763 /**
1764 * Note: we are overriding this method to remove the deprecated error
1765 * @see https://phabricator.wikimedia.org/T71505
1766 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1767 * @deprecated
1768 *
1769 * @param array $matcher
1770 * @param string $actual
1771 * @param string $message
1772 * @param bool $isHtml
1773 */
1774 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1775 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1776
1777 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1778 }
1779
1780 /**
1781 * @see MediaWikiTestCase::assertTag
1782 * @deprecated
1783 *
1784 * @param array $matcher
1785 * @param string $actual
1786 * @param string $message
1787 * @param bool $isHtml
1788 */
1789 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1790 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1791
1792 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1793 }
1794
1795 /**
1796 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1797 * @return string
1798 */
1799 public static function wfResetOutputBuffersBarrier( $buffer ) {
1800 return $buffer;
1801 }
1802
1803 /**
1804 * Create a temporary hook handler which will be reset by tearDown.
1805 * This replaces other handlers for the same hook.
1806 * @param string $hookName Hook name
1807 * @param mixed $handler Value suitable for a hook handler
1808 * @since 1.28
1809 */
1810 protected function setTemporaryHook( $hookName, $handler ) {
1811 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
1812 }
1813
1814 }