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