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