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