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