Merge "Show protection log on creation-protected pages"
[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 * @par 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 * @endcode
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 | 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
1258 protected static function getExternalStoreDatabaseConnections() {
1259 global $wgDefaultExternalStore;
1260
1261 /** @var ExternalStoreDB $externalStoreDB */
1262 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1263 $defaultArray = (array)$wgDefaultExternalStore;
1264 $dbws = [];
1265 foreach ( $defaultArray as $url ) {
1266 if ( strpos( $url, 'DB://' ) === 0 ) {
1267 list( $proto, $cluster ) = explode( '://', $url, 2 );
1268 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1269 // requires Database instead of plain DBConnRef/IDatabase
1270 $dbws[] = $externalStoreDB->getMaster( $cluster );
1271 }
1272 }
1273
1274 return $dbws;
1275 }
1276
1277 /**
1278 * Check whether ExternalStoreDB is being used
1279 *
1280 * @return bool True if it's being used
1281 */
1282 protected static function isUsingExternalStoreDB() {
1283 global $wgDefaultExternalStore;
1284 if ( !$wgDefaultExternalStore ) {
1285 return false;
1286 }
1287
1288 $defaultArray = (array)$wgDefaultExternalStore;
1289 foreach ( $defaultArray as $url ) {
1290 if ( strpos( $url, 'DB://' ) === 0 ) {
1291 return true;
1292 }
1293 }
1294
1295 return false;
1296 }
1297
1298 /**
1299 * Empty all tables so they can be repopulated for tests
1300 *
1301 * @param Database $db|null Database to reset
1302 * @param array $tablesUsed Tables to reset
1303 */
1304 private function resetDB( $db, $tablesUsed ) {
1305 if ( $db ) {
1306 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1307 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1308
1309 // If any of the user 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
1315 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1316 foreach ( $tablesUsed as $tbl ) {
1317 // TODO: reset interwiki table to its original content.
1318 if ( $tbl == 'interwiki' ) {
1319 continue;
1320 }
1321
1322 if ( $truncate ) {
1323 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1324 } else {
1325 $db->delete( $tbl, '*', __METHOD__ );
1326 }
1327
1328 if ( $tbl === 'page' ) {
1329 // Forget about the pages since they don't
1330 // exist in the DB.
1331 LinkCache::singleton()->clear();
1332 }
1333 }
1334
1335 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1336 // Re-add core DB data that was deleted
1337 $this->addCoreDBData();
1338 }
1339 }
1340 }
1341
1342 /**
1343 * @since 1.18
1344 *
1345 * @param string $func
1346 * @param array $args
1347 *
1348 * @return mixed
1349 * @throws MWException
1350 */
1351 public function __call( $func, $args ) {
1352 static $compatibility = [
1353 'createMock' => 'createMock2',
1354 ];
1355
1356 if ( isset( $compatibility[$func] ) ) {
1357 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1358 } else {
1359 throw new MWException( "Called non-existent $func method on " . static::class );
1360 }
1361 }
1362
1363 /**
1364 * Return a test double for the specified class.
1365 *
1366 * @param string $originalClassName
1367 * @return PHPUnit_Framework_MockObject_MockObject
1368 * @throws Exception
1369 */
1370 private function createMock2( $originalClassName ) {
1371 return $this->getMockBuilder( $originalClassName )
1372 ->disableOriginalConstructor()
1373 ->disableOriginalClone()
1374 ->disableArgumentCloning()
1375 // New in phpunit-mock-objects 3.2 (phpunit 5.4.0)
1376 // ->disallowMockingUnknownTypes()
1377 ->getMock();
1378 }
1379
1380 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1381 $tableName = substr( $tableName, strlen( $prefix ) );
1382 }
1383
1384 private static function isNotUnittest( $table ) {
1385 return strpos( $table, 'unittest_' ) !== 0;
1386 }
1387
1388 /**
1389 * @since 1.18
1390 *
1391 * @param IMaintainableDatabase $db
1392 *
1393 * @return array
1394 */
1395 public static function listTables( IMaintainableDatabase $db ) {
1396 $prefix = $db->tablePrefix();
1397 $tables = $db->listTables( $prefix, __METHOD__ );
1398
1399 if ( $db->getType() === 'mysql' ) {
1400 static $viewListCache = null;
1401 if ( $viewListCache === null ) {
1402 $viewListCache = $db->listViews( null, __METHOD__ );
1403 }
1404 // T45571: cannot clone VIEWs under MySQL
1405 $tables = array_diff( $tables, $viewListCache );
1406 }
1407 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1408
1409 // Don't duplicate test tables from the previous fataled run
1410 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1411
1412 if ( $db->getType() == 'sqlite' ) {
1413 $tables = array_flip( $tables );
1414 // these are subtables of searchindex and don't need to be duped/dropped separately
1415 unset( $tables['searchindex_content'] );
1416 unset( $tables['searchindex_segdir'] );
1417 unset( $tables['searchindex_segments'] );
1418 $tables = array_flip( $tables );
1419 }
1420
1421 return $tables;
1422 }
1423
1424 /**
1425 * @throws MWException
1426 * @since 1.18
1427 */
1428 protected function checkDbIsSupported() {
1429 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1430 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1431 }
1432 }
1433
1434 /**
1435 * @since 1.18
1436 * @param string $offset
1437 * @return mixed
1438 */
1439 public function getCliArg( $offset ) {
1440 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1441 return PHPUnitMaintClass::$additionalOptions[$offset];
1442 }
1443
1444 return null;
1445 }
1446
1447 /**
1448 * @since 1.18
1449 * @param string $offset
1450 * @param mixed $value
1451 */
1452 public function setCliArg( $offset, $value ) {
1453 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1454 }
1455
1456 /**
1457 * Don't throw a warning if $function is deprecated and called later
1458 *
1459 * @since 1.19
1460 *
1461 * @param string $function
1462 */
1463 public function hideDeprecated( $function ) {
1464 MediaWiki\suppressWarnings();
1465 wfDeprecated( $function );
1466 MediaWiki\restoreWarnings();
1467 }
1468
1469 /**
1470 * Asserts that the given database query yields the rows given by $expectedRows.
1471 * The expected rows should be given as indexed (not associative) arrays, with
1472 * the values given in the order of the columns in the $fields parameter.
1473 * Note that the rows are sorted by the columns given in $fields.
1474 *
1475 * @since 1.20
1476 *
1477 * @param string|array $table The table(s) to query
1478 * @param string|array $fields The columns to include in the result (and to sort by)
1479 * @param string|array $condition "where" condition(s)
1480 * @param array $expectedRows An array of arrays giving the expected rows.
1481 *
1482 * @throws MWException If this test cases's needsDB() method doesn't return true.
1483 * Test cases can use "@group Database" to enable database test support,
1484 * or list the tables under testing in $this->tablesUsed, or override the
1485 * needsDB() method.
1486 */
1487 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1488 if ( !$this->needsDB() ) {
1489 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1490 ' method should return true. Use @group Database or $this->tablesUsed.' );
1491 }
1492
1493 $db = wfGetDB( DB_REPLICA );
1494
1495 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1496 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1497
1498 $i = 0;
1499
1500 foreach ( $expectedRows as $expected ) {
1501 $r = $res->fetchRow();
1502 self::stripStringKeys( $r );
1503
1504 $i += 1;
1505 $this->assertNotEmpty( $r, "row #$i missing" );
1506
1507 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1508 }
1509
1510 $r = $res->fetchRow();
1511 self::stripStringKeys( $r );
1512
1513 $this->assertFalse( $r, "found extra row (after #$i)" );
1514 }
1515
1516 /**
1517 * Utility method taking an array of elements and wrapping
1518 * each element in its own array. Useful for data providers
1519 * that only return a single argument.
1520 *
1521 * @since 1.20
1522 *
1523 * @param array $elements
1524 *
1525 * @return array
1526 */
1527 protected function arrayWrap( array $elements ) {
1528 return array_map(
1529 function ( $element ) {
1530 return [ $element ];
1531 },
1532 $elements
1533 );
1534 }
1535
1536 /**
1537 * Assert that two arrays are equal. By default this means that both arrays need to hold
1538 * the same set of values. Using additional arguments, order and associated key can also
1539 * be set as relevant.
1540 *
1541 * @since 1.20
1542 *
1543 * @param array $expected
1544 * @param array $actual
1545 * @param bool $ordered If the order of the values should match
1546 * @param bool $named If the keys should match
1547 */
1548 protected function assertArrayEquals( array $expected, array $actual,
1549 $ordered = false, $named = false
1550 ) {
1551 if ( !$ordered ) {
1552 $this->objectAssociativeSort( $expected );
1553 $this->objectAssociativeSort( $actual );
1554 }
1555
1556 if ( !$named ) {
1557 $expected = array_values( $expected );
1558 $actual = array_values( $actual );
1559 }
1560
1561 call_user_func_array(
1562 [ $this, 'assertEquals' ],
1563 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1564 );
1565 }
1566
1567 /**
1568 * Put each HTML element on its own line and then equals() the results
1569 *
1570 * Use for nicely formatting of PHPUnit diff output when comparing very
1571 * simple HTML
1572 *
1573 * @since 1.20
1574 *
1575 * @param string $expected HTML on oneline
1576 * @param string $actual HTML on oneline
1577 * @param string $msg Optional message
1578 */
1579 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1580 $expected = str_replace( '>', ">\n", $expected );
1581 $actual = str_replace( '>', ">\n", $actual );
1582
1583 $this->assertEquals( $expected, $actual, $msg );
1584 }
1585
1586 /**
1587 * Does an associative sort that works for objects.
1588 *
1589 * @since 1.20
1590 *
1591 * @param array $array
1592 */
1593 protected function objectAssociativeSort( array &$array ) {
1594 uasort(
1595 $array,
1596 function ( $a, $b ) {
1597 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1598 }
1599 );
1600 }
1601
1602 /**
1603 * Utility function for eliminating all string keys from an array.
1604 * Useful to turn a database result row as returned by fetchRow() into
1605 * a pure indexed array.
1606 *
1607 * @since 1.20
1608 *
1609 * @param mixed $r The array to remove string keys from.
1610 */
1611 protected static function stripStringKeys( &$r ) {
1612 if ( !is_array( $r ) ) {
1613 return;
1614 }
1615
1616 foreach ( $r as $k => $v ) {
1617 if ( is_string( $k ) ) {
1618 unset( $r[$k] );
1619 }
1620 }
1621 }
1622
1623 /**
1624 * Asserts that the provided variable is of the specified
1625 * internal type or equals the $value argument. This is useful
1626 * for testing return types of functions that return a certain
1627 * type or *value* when not set or on error.
1628 *
1629 * @since 1.20
1630 *
1631 * @param string $type
1632 * @param mixed $actual
1633 * @param mixed $value
1634 * @param string $message
1635 */
1636 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1637 if ( $actual === $value ) {
1638 $this->assertTrue( true, $message );
1639 } else {
1640 $this->assertType( $type, $actual, $message );
1641 }
1642 }
1643
1644 /**
1645 * Asserts the type of the provided value. This can be either
1646 * in internal type such as boolean or integer, or a class or
1647 * interface the value extends or implements.
1648 *
1649 * @since 1.20
1650 *
1651 * @param string $type
1652 * @param mixed $actual
1653 * @param string $message
1654 */
1655 protected function assertType( $type, $actual, $message = '' ) {
1656 if ( class_exists( $type ) || interface_exists( $type ) ) {
1657 $this->assertInstanceOf( $type, $actual, $message );
1658 } else {
1659 $this->assertInternalType( $type, $actual, $message );
1660 }
1661 }
1662
1663 /**
1664 * Returns true if the given namespace defaults to Wikitext
1665 * according to $wgNamespaceContentModels
1666 *
1667 * @param int $ns The namespace ID to check
1668 *
1669 * @return bool
1670 * @since 1.21
1671 */
1672 protected function isWikitextNS( $ns ) {
1673 global $wgNamespaceContentModels;
1674
1675 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1676 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1677 }
1678
1679 return true;
1680 }
1681
1682 /**
1683 * Returns the ID of a namespace that defaults to Wikitext.
1684 *
1685 * @throws MWException If there is none.
1686 * @return int The ID of the wikitext Namespace
1687 * @since 1.21
1688 */
1689 protected function getDefaultWikitextNS() {
1690 global $wgNamespaceContentModels;
1691
1692 static $wikitextNS = null; // this is not going to change
1693 if ( $wikitextNS !== null ) {
1694 return $wikitextNS;
1695 }
1696
1697 // quickly short out on most common case:
1698 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1699 return NS_MAIN;
1700 }
1701
1702 // NOTE: prefer content namespaces
1703 $namespaces = array_unique( array_merge(
1704 MWNamespace::getContentNamespaces(),
1705 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1706 MWNamespace::getValidNamespaces()
1707 ) );
1708
1709 $namespaces = array_diff( $namespaces, [
1710 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1711 ] );
1712
1713 $talk = array_filter( $namespaces, function ( $ns ) {
1714 return MWNamespace::isTalk( $ns );
1715 } );
1716
1717 // prefer non-talk pages
1718 $namespaces = array_diff( $namespaces, $talk );
1719 $namespaces = array_merge( $namespaces, $talk );
1720
1721 // check default content model of each namespace
1722 foreach ( $namespaces as $ns ) {
1723 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1724 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1725 ) {
1726 $wikitextNS = $ns;
1727
1728 return $wikitextNS;
1729 }
1730 }
1731
1732 // give up
1733 // @todo Inside a test, we could skip the test as incomplete.
1734 // But frequently, this is used in fixture setup.
1735 throw new MWException( "No namespace defaults to wikitext!" );
1736 }
1737
1738 /**
1739 * Check, if $wgDiff3 is set and ready to merge
1740 * Will mark the calling test as skipped, if not ready
1741 *
1742 * @since 1.21
1743 */
1744 protected function markTestSkippedIfNoDiff3() {
1745 global $wgDiff3;
1746
1747 # This check may also protect against code injection in
1748 # case of broken installations.
1749 MediaWiki\suppressWarnings();
1750 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1751 MediaWiki\restoreWarnings();
1752
1753 if ( !$haveDiff3 ) {
1754 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1755 }
1756 }
1757
1758 /**
1759 * Check if $extName is a loaded PHP extension, will skip the
1760 * test whenever it is not loaded.
1761 *
1762 * @since 1.21
1763 * @param string $extName
1764 * @return bool
1765 */
1766 protected function checkPHPExtension( $extName ) {
1767 $loaded = extension_loaded( $extName );
1768 if ( !$loaded ) {
1769 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1770 }
1771
1772 return $loaded;
1773 }
1774
1775 /**
1776 * Asserts that the given string is a valid HTML snippet.
1777 * Wraps the given string in the required top level tags and
1778 * then calls assertValidHtmlDocument().
1779 * The snippet is expected to be HTML 5.
1780 *
1781 * @since 1.23
1782 *
1783 * @note Will mark the test as skipped if the "tidy" module is not installed.
1784 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1785 * when automatic tidying is disabled.
1786 *
1787 * @param string $html An HTML snippet (treated as the contents of the body tag).
1788 */
1789 protected function assertValidHtmlSnippet( $html ) {
1790 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1791 $this->assertValidHtmlDocument( $html );
1792 }
1793
1794 /**
1795 * Asserts that the given string is valid HTML document.
1796 *
1797 * @since 1.23
1798 *
1799 * @note Will mark the test as skipped if the "tidy" module is not installed.
1800 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1801 * when automatic tidying is disabled.
1802 *
1803 * @param string $html A complete HTML document
1804 */
1805 protected function assertValidHtmlDocument( $html ) {
1806 // Note: we only validate if the tidy PHP extension is available.
1807 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1808 // of tidy. In that case however, we can not reliably detect whether a failing validation
1809 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1810 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1811 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1812 $this->markTestSkipped( 'Tidy extension not installed' );
1813 }
1814
1815 $errorBuffer = '';
1816 MWTidy::checkErrors( $html, $errorBuffer );
1817 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1818
1819 // Filter Tidy warnings which aren't useful for us.
1820 // Tidy eg. often cries about parameters missing which have actually
1821 // been deprecated since HTML4, thus we should not care about them.
1822 $errors = preg_grep(
1823 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1824 $allErrors, PREG_GREP_INVERT
1825 );
1826
1827 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1828 }
1829
1830 /**
1831 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1832 * @return string
1833 */
1834 public static function wfResetOutputBuffersBarrier( $buffer ) {
1835 return $buffer;
1836 }
1837
1838 /**
1839 * Create a temporary hook handler which will be reset by tearDown.
1840 * This replaces other handlers for the same hook.
1841 * @param string $hookName Hook name
1842 * @param mixed $handler Value suitable for a hook handler
1843 * @since 1.28
1844 */
1845 protected function setTemporaryHook( $hookName, $handler ) {
1846 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
1847 }
1848
1849 }