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