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