Merge "Add rc_name_type_patrolled_timestamp index"
[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 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
486 }
487
488 protected function addTmpFiles( $files ) {
489 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
490 }
491
492 protected function tearDown() {
493 global $wgRequest;
494
495 $status = ob_get_status();
496 if ( isset( $status['name'] ) &&
497 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
498 ) {
499 ob_end_flush();
500 }
501
502 $this->called['tearDown'] = true;
503 // Cleaning up temporary files
504 foreach ( $this->tmpFiles as $fileName ) {
505 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
506 unlink( $fileName );
507 } elseif ( is_dir( $fileName ) ) {
508 wfRecursiveRemoveDir( $fileName );
509 }
510 }
511
512 if ( $this->needsDB() && $this->db ) {
513 // Clean up open transactions
514 while ( $this->db->trxLevel() > 0 ) {
515 $this->db->rollback( __METHOD__, 'flush' );
516 }
517 }
518
519 // Restore mw globals
520 foreach ( $this->mwGlobals as $key => $value ) {
521 $GLOBALS[$key] = $value;
522 }
523 $this->mwGlobals = [];
524 $this->restoreLoggers();
525
526 if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
527 MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
528 }
529
530 // TODO: move global state into MediaWikiServices
531 RequestContext::resetMain();
532 if ( session_id() !== '' ) {
533 session_write_close();
534 session_id( '' );
535 }
536 $wgRequest = new FauxRequest();
537 MediaWiki\Session\SessionManager::resetCache();
538 MediaWiki\Auth\AuthManager::resetCache();
539
540 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
541
542 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
543 ini_set( 'error_reporting', $this->phpErrorLevel );
544
545 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
546 $newHex = strtoupper( dechex( $phpErrorLevel ) );
547 $message = "PHP error_reporting setting was left dirty: "
548 . "was 0x$oldHex before test, 0x$newHex after test!";
549
550 $this->fail( $message );
551 }
552
553 parent::tearDown();
554 }
555
556 /**
557 * Make sure MediaWikiTestCase extending classes have called their
558 * parent setUp method
559 */
560 final public function testMediaWikiTestCaseParentSetupCalled() {
561 $this->assertArrayHasKey( 'setUp', $this->called,
562 static::class . '::setUp() must call parent::setUp()'
563 );
564 }
565
566 /**
567 * Sets a service, maintaining a stashed version of the previous service to be
568 * restored in tearDown
569 *
570 * @since 1.27
571 *
572 * @param string $name
573 * @param object $object
574 */
575 protected function setService( $name, $object ) {
576 // If we did not yet override the service locator, so so now.
577 if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
578 $this->overrideMwServices();
579 }
580
581 MediaWikiServices::getInstance()->disableService( $name );
582 MediaWikiServices::getInstance()->redefineService(
583 $name,
584 function () use ( $object ) {
585 return $object;
586 }
587 );
588 }
589
590 /**
591 * Sets a global, maintaining a stashed version of the previous global to be
592 * restored in tearDown
593 *
594 * The key is added to the array of globals that will be reset afterwards
595 * in the tearDown().
596 *
597 * @example
598 * <code>
599 * protected function setUp() {
600 * $this->setMwGlobals( 'wgRestrictStuff', true );
601 * }
602 *
603 * function testFoo() {}
604 *
605 * function testBar() {}
606 * $this->assertTrue( self::getX()->doStuff() );
607 *
608 * $this->setMwGlobals( 'wgRestrictStuff', false );
609 * $this->assertTrue( self::getX()->doStuff() );
610 * }
611 *
612 * function testQuux() {}
613 * </code>
614 *
615 * @param array|string $pairs Key to the global variable, or an array
616 * of key/value pairs.
617 * @param mixed $value Value to set the global to (ignored
618 * if an array is given as first argument).
619 *
620 * @note To allow changes to global variables to take effect on global service instances,
621 * call overrideMwServices().
622 *
623 * @since 1.21
624 */
625 protected function setMwGlobals( $pairs, $value = null ) {
626 if ( is_string( $pairs ) ) {
627 $pairs = [ $pairs => $value ];
628 }
629
630 $this->stashMwGlobals( array_keys( $pairs ) );
631
632 foreach ( $pairs as $key => $value ) {
633 $GLOBALS[$key] = $value;
634 }
635 }
636
637 /**
638 * Check if we can back up a value by performing a shallow copy.
639 * Values which fail this test are copied recursively.
640 *
641 * @param mixed $value
642 * @return bool True if a shallow copy will do; false if a deep copy
643 * is required.
644 */
645 private static function canShallowCopy( $value ) {
646 if ( is_scalar( $value ) || $value === null ) {
647 return true;
648 }
649 if ( is_array( $value ) ) {
650 foreach ( $value as $subValue ) {
651 if ( !is_scalar( $subValue ) && $subValue !== null ) {
652 return false;
653 }
654 }
655 return true;
656 }
657 return false;
658 }
659
660 /**
661 * Stashes the global, will be restored in tearDown()
662 *
663 * Individual test functions may override globals through the setMwGlobals() function
664 * or directly. When directly overriding globals their keys should first be passed to this
665 * method in setUp to avoid breaking global state for other tests
666 *
667 * That way all other tests are executed with the same settings (instead of using the
668 * unreliable local settings for most tests and fix it only for some tests).
669 *
670 * @param array|string $globalKeys Key to the global variable, or an array of keys.
671 *
672 * @throws Exception When trying to stash an unset global
673 *
674 * @note To allow changes to global variables to take effect on global service instances,
675 * call overrideMwServices().
676 *
677 * @since 1.23
678 */
679 protected function stashMwGlobals( $globalKeys ) {
680 if ( is_string( $globalKeys ) ) {
681 $globalKeys = [ $globalKeys ];
682 }
683
684 foreach ( $globalKeys as $globalKey ) {
685 // NOTE: make sure we only save the global once or a second call to
686 // setMwGlobals() on the same global would override the original
687 // value.
688 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
689 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
690 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
691 }
692 // NOTE: we serialize then unserialize the value in case it is an object
693 // this stops any objects being passed by reference. We could use clone
694 // and if is_object but this does account for objects within objects!
695 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
696 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
697 } elseif (
698 // Many MediaWiki types are safe to clone. These are the
699 // ones that are most commonly stashed.
700 $GLOBALS[$globalKey] instanceof Language ||
701 $GLOBALS[$globalKey] instanceof User ||
702 $GLOBALS[$globalKey] instanceof FauxRequest
703 ) {
704 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
705 } else {
706 try {
707 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
708 } catch ( Exception $e ) {
709 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
710 }
711 }
712 }
713 }
714 }
715
716 /**
717 * Merges the given values into a MW global array variable.
718 * Useful for setting some entries in a configuration array, instead of
719 * setting the entire array.
720 *
721 * @param string $name The name of the global, as in wgFooBar
722 * @param array $values The array containing the entries to set in that global
723 *
724 * @throws MWException If the designated global is not an array.
725 *
726 * @note To allow changes to global variables to take effect on global service instances,
727 * call overrideMwServices().
728 *
729 * @since 1.21
730 */
731 protected function mergeMwGlobalArrayValue( $name, $values ) {
732 if ( !isset( $GLOBALS[$name] ) ) {
733 $merged = $values;
734 } else {
735 if ( !is_array( $GLOBALS[$name] ) ) {
736 throw new MWException( "MW global $name is not an array." );
737 }
738
739 // NOTE: do not use array_merge, it screws up for numeric keys.
740 $merged = $GLOBALS[$name];
741 foreach ( $values as $k => $v ) {
742 $merged[$k] = $v;
743 }
744 }
745
746 $this->setMwGlobals( $name, $merged );
747 }
748
749 /**
750 * Stashes the global instance of MediaWikiServices, and installs a new one,
751 * allowing test cases to override settings and services.
752 * The previous instance of MediaWikiServices will be restored on tearDown.
753 *
754 * @since 1.27
755 *
756 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
757 * @param callable[] $services An associative array of services to re-define. Keys are service
758 * names, values are callables.
759 *
760 * @return MediaWikiServices
761 * @throws MWException
762 */
763 protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
764 if ( !$configOverrides ) {
765 $configOverrides = new HashConfig();
766 }
767
768 $oldInstance = MediaWikiServices::getInstance();
769 $oldConfigFactory = $oldInstance->getConfigFactory();
770
771 $testConfig = self::makeTestConfig( null, $configOverrides );
772 $newInstance = new MediaWikiServices( $testConfig );
773
774 // Load the default wiring from the specified files.
775 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
776 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
777 $newInstance->loadWiringFiles( $wiringFiles );
778
779 // Provide a traditional hook point to allow extensions to configure services.
780 Hooks::run( 'MediaWikiServices', [ $newInstance ] );
781
782 foreach ( $services as $name => $callback ) {
783 $newInstance->redefineService( $name, $callback );
784 }
785
786 self::installTestServices(
787 $oldConfigFactory,
788 $newInstance
789 );
790 MediaWikiServices::forceGlobalInstance( $newInstance );
791
792 return $newInstance;
793 }
794
795 /**
796 * @since 1.27
797 * @param string|Language $lang
798 */
799 public function setUserLang( $lang ) {
800 RequestContext::getMain()->setLanguage( $lang );
801 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
802 }
803
804 /**
805 * @since 1.27
806 * @param string|Language $lang
807 */
808 public function setContentLang( $lang ) {
809 if ( $lang instanceof Language ) {
810 $langCode = $lang->getCode();
811 $langObj = $lang;
812 } else {
813 $langCode = $lang;
814 $langObj = Language::factory( $langCode );
815 }
816 $this->setMwGlobals( [
817 'wgLanguageCode' => $langCode,
818 'wgContLang' => $langObj,
819 ] );
820 }
821
822 /**
823 * Sets the logger for a specified channel, for the duration of the test.
824 * @since 1.27
825 * @param string $channel
826 * @param LoggerInterface $logger
827 */
828 protected function setLogger( $channel, LoggerInterface $logger ) {
829 // TODO: Once loggers are managed by MediaWikiServices, use
830 // overrideMwServices() to set loggers.
831
832 $provider = LoggerFactory::getProvider();
833 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
834 $singletons = $wrappedProvider->singletons;
835 if ( $provider instanceof MonologSpi ) {
836 if ( !isset( $this->loggers[$channel] ) ) {
837 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
838 ? $singletons['loggers'][$channel] : null;
839 }
840 $singletons['loggers'][$channel] = $logger;
841 } elseif ( $provider instanceof LegacySpi ) {
842 if ( !isset( $this->loggers[$channel] ) ) {
843 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
844 }
845 $singletons[$channel] = $logger;
846 } else {
847 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
848 . ' is not implemented' );
849 }
850 $wrappedProvider->singletons = $singletons;
851 }
852
853 /**
854 * Restores loggers replaced by setLogger().
855 * @since 1.27
856 */
857 private function restoreLoggers() {
858 $provider = LoggerFactory::getProvider();
859 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
860 $singletons = $wrappedProvider->singletons;
861 foreach ( $this->loggers as $channel => $logger ) {
862 if ( $provider instanceof MonologSpi ) {
863 if ( $logger === null ) {
864 unset( $singletons['loggers'][$channel] );
865 } else {
866 $singletons['loggers'][$channel] = $logger;
867 }
868 } elseif ( $provider instanceof LegacySpi ) {
869 if ( $logger === null ) {
870 unset( $singletons[$channel] );
871 } else {
872 $singletons[$channel] = $logger;
873 }
874 }
875 }
876 $wrappedProvider->singletons = $singletons;
877 $this->loggers = [];
878 }
879
880 /**
881 * @return string
882 * @since 1.18
883 */
884 public function dbPrefix() {
885 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
886 }
887
888 /**
889 * @return bool
890 * @since 1.18
891 */
892 public function needsDB() {
893 # if the test says it uses database tables, it needs the database
894 if ( $this->tablesUsed ) {
895 return true;
896 }
897
898 # if the test says it belongs to the Database group, it needs the database
899 $rc = new ReflectionClass( $this );
900 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
901 return true;
902 }
903
904 return false;
905 }
906
907 /**
908 * Insert a new page.
909 *
910 * Should be called from addDBData().
911 *
912 * @since 1.25
913 * @param string $pageName Page name
914 * @param string $text Page's content
915 * @return array Title object and page id
916 */
917 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
918 $title = Title::newFromText( $pageName, 0 );
919
920 $user = static::getTestSysop()->getUser();
921 $comment = __METHOD__ . ': Sample page for unit test.';
922
923 // Avoid memory leak...?
924 // LinkCache::singleton()->clear();
925 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
926
927 $page = WikiPage::factory( $title );
928 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
929
930 return [
931 'title' => $title,
932 'id' => $page->getId(),
933 ];
934 }
935
936 /**
937 * Stub. If a test suite needs to add additional data to the database, it should
938 * implement this method and do so. This method is called once per test suite
939 * (i.e. once per class).
940 *
941 * Note data added by this method may be removed by resetDB() depending on
942 * the contents of $tablesUsed.
943 *
944 * To add additional data between test function runs, override prepareDB().
945 *
946 * @see addDBData()
947 * @see resetDB()
948 *
949 * @since 1.27
950 */
951 public function addDBDataOnce() {
952 }
953
954 /**
955 * Stub. Subclasses may override this to prepare the database.
956 * Called before every test run (test function or data set).
957 *
958 * @see addDBDataOnce()
959 * @see resetDB()
960 *
961 * @since 1.18
962 */
963 public function addDBData() {
964 }
965
966 private function addCoreDBData() {
967 if ( $this->db->getType() == 'oracle' ) {
968
969 # Insert 0 user to prevent FK violations
970 # Anonymous user
971 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
972 $this->db->insert( 'user', [
973 'user_id' => 0,
974 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
975 }
976
977 # Insert 0 page to prevent FK violations
978 # Blank page
979 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
980 $this->db->insert( 'page', [
981 'page_id' => 0,
982 'page_namespace' => 0,
983 'page_title' => ' ',
984 'page_restrictions' => null,
985 'page_is_redirect' => 0,
986 'page_is_new' => 0,
987 'page_random' => 0,
988 'page_touched' => $this->db->timestamp(),
989 'page_latest' => 0,
990 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
991 }
992 }
993
994 User::resetIdByNameCache();
995
996 // Make sysop user
997 $user = static::getTestSysop()->getUser();
998
999 // Make 1 page with 1 revision
1000 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1001 if ( $page->getId() == 0 ) {
1002 $page->doEditContent(
1003 new WikitextContent( 'UTContent' ),
1004 'UTPageSummary',
1005 EDIT_NEW,
1006 false,
1007 $user
1008 );
1009
1010 // doEditContent() probably started the session via
1011 // User::loadFromSession(). Close it now.
1012 if ( session_id() !== '' ) {
1013 session_write_close();
1014 session_id( '' );
1015 }
1016 }
1017 }
1018
1019 /**
1020 * Restores MediaWiki to using the table set (table prefix) it was using before
1021 * setupTestDB() was called. Useful if we need to perform database operations
1022 * after the test run has finished (such as saving logs or profiling info).
1023 *
1024 * @since 1.21
1025 */
1026 public static function teardownTestDB() {
1027 global $wgJobClasses;
1028
1029 if ( !self::$dbSetup ) {
1030 return;
1031 }
1032
1033 foreach ( $wgJobClasses as $type => $class ) {
1034 // Delete any jobs under the clone DB (or old prefix in other stores)
1035 JobQueueGroup::singleton()->get( $type )->delete();
1036 }
1037
1038 CloneDatabase::changePrefix( self::$oldTablePrefix );
1039
1040 self::$oldTablePrefix = false;
1041 self::$dbSetup = false;
1042 }
1043
1044 /**
1045 * Setups a database with the given prefix.
1046 *
1047 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1048 * Otherwise, it will clone the tables and change the prefix.
1049 *
1050 * Clones all tables in the given database (whatever database that connection has
1051 * open), to versions with the test prefix.
1052 *
1053 * @param DatabaseBase $db Database to use
1054 * @param string $prefix Prefix to use for test tables
1055 * @return bool True if tables were cloned, false if only the prefix was changed
1056 */
1057 protected static function setupDatabaseWithTestPrefix( DatabaseBase $db, $prefix ) {
1058 $tablesCloned = self::listTables( $db );
1059 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1060 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1061
1062 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1063 CloneDatabase::changePrefix( $prefix );
1064
1065 return false;
1066 } else {
1067 $dbClone->cloneTableStructure();
1068 return true;
1069 }
1070 }
1071
1072 /**
1073 * Set up all test DBs
1074 */
1075 public function setupAllTestDBs() {
1076 global $wgDBprefix;
1077
1078 self::$oldTablePrefix = $wgDBprefix;
1079
1080 $testPrefix = $this->dbPrefix();
1081
1082 // switch to a temporary clone of the database
1083 self::setupTestDB( $this->db, $testPrefix );
1084
1085 if ( self::isUsingExternalStoreDB() ) {
1086 self::setupExternalStoreTestDBs( $testPrefix );
1087 }
1088 }
1089
1090 /**
1091 * Creates an empty skeleton of the wiki database by cloning its structure
1092 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1093 * use the new set of tables (aka schema) instead of the original set.
1094 *
1095 * This is used to generate a dummy table set, typically consisting of temporary
1096 * tables, that will be used by tests instead of the original wiki database tables.
1097 *
1098 * @since 1.21
1099 *
1100 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1101 * by teardownTestDB() to return the wiki to using the original table set.
1102 *
1103 * @note this method only works when first called. Subsequent calls have no effect,
1104 * even if using different parameters.
1105 *
1106 * @param DatabaseBase $db The database connection
1107 * @param string $prefix The prefix to use for the new table set (aka schema).
1108 *
1109 * @throws MWException If the database table prefix is already $prefix
1110 */
1111 public static function setupTestDB( DatabaseBase $db, $prefix ) {
1112 if ( $db->tablePrefix() === $prefix ) {
1113 throw new MWException(
1114 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1115 }
1116
1117 if ( self::$dbSetup ) {
1118 return;
1119 }
1120
1121 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1122 // and DatabaseBase no longer use global state.
1123
1124 self::$dbSetup = true;
1125
1126 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1127 return;
1128 }
1129
1130 // Assuming this isn't needed for External Store database, and not sure if the procedure
1131 // would be available there.
1132 if ( $db->getType() == 'oracle' ) {
1133 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1134 }
1135 }
1136
1137 /**
1138 * Clones the External Store database(s) for testing
1139 *
1140 * @param string $testPrefix Prefix for test tables
1141 */
1142 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1143 $connections = self::getExternalStoreDatabaseConnections();
1144 foreach ( $connections as $dbw ) {
1145 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1146 // prefix,. Even though listTables now uses tablePrefix, that
1147 // itself is populated from $wgDBprefix by default.
1148
1149 // We have to set it back, or we won't find the original 'blobs'
1150 // table to copy.
1151
1152 $dbw->tablePrefix( self::$oldTablePrefix );
1153 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1154 }
1155 }
1156
1157 /**
1158 * Gets master database connections for all of the ExternalStoreDB
1159 * stores configured in $wgDefaultExternalStore.
1160 *
1161 * @return array Array of DatabaseBase master connections
1162 */
1163
1164 protected static function getExternalStoreDatabaseConnections() {
1165 global $wgDefaultExternalStore;
1166
1167 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1168 $defaultArray = (array) $wgDefaultExternalStore;
1169 $dbws = [];
1170 foreach ( $defaultArray as $url ) {
1171 if ( strpos( $url, 'DB://' ) === 0 ) {
1172 list( $proto, $cluster ) = explode( '://', $url, 2 );
1173 $dbw = $externalStoreDB->getMaster( $cluster );
1174 $dbws[] = $dbw;
1175 }
1176 }
1177
1178 return $dbws;
1179 }
1180
1181 /**
1182 * Check whether ExternalStoreDB is being used
1183 *
1184 * @return bool True if it's being used
1185 */
1186 protected static function isUsingExternalStoreDB() {
1187 global $wgDefaultExternalStore;
1188 if ( !$wgDefaultExternalStore ) {
1189 return false;
1190 }
1191
1192 $defaultArray = (array) $wgDefaultExternalStore;
1193 foreach ( $defaultArray as $url ) {
1194 if ( strpos( $url, 'DB://' ) === 0 ) {
1195 return true;
1196 }
1197 }
1198
1199 return false;
1200 }
1201
1202 /**
1203 * Empty all tables so they can be repopulated for tests
1204 *
1205 * @param DatabaseBase $db|null Database to reset
1206 * @param array $tablesUsed Tables to reset
1207 */
1208 private function resetDB( $db, $tablesUsed ) {
1209 if ( $db ) {
1210 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1211 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1212
1213 // If any of the user tables were marked as used, we should clear all of them.
1214 if ( array_intersect( $tablesUsed, $userTables ) ) {
1215 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1216 TestUserRegistry::clear();
1217 }
1218
1219 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1220 foreach ( $tablesUsed as $tbl ) {
1221 // TODO: reset interwiki table to its original content.
1222 if ( $tbl == 'interwiki' ) {
1223 continue;
1224 }
1225
1226 if ( $truncate ) {
1227 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1228 } else {
1229 $db->delete( $tbl, '*', __METHOD__ );
1230 }
1231
1232 if ( $tbl === 'page' ) {
1233 // Forget about the pages since they don't
1234 // exist in the DB.
1235 LinkCache::singleton()->clear();
1236 }
1237 }
1238
1239 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1240 // Re-add core DB data that was deleted
1241 $this->addCoreDBData();
1242 }
1243 }
1244 }
1245
1246 /**
1247 * @since 1.18
1248 *
1249 * @param string $func
1250 * @param array $args
1251 *
1252 * @return mixed
1253 * @throws MWException
1254 */
1255 public function __call( $func, $args ) {
1256 static $compatibility = [
1257 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1258 ];
1259
1260 if ( isset( $compatibility[$func] ) ) {
1261 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1262 } else {
1263 throw new MWException( "Called non-existent $func method on "
1264 . get_class( $this ) );
1265 }
1266 }
1267
1268 /**
1269 * Used as a compatibility method for phpunit < 3.7.32
1270 * @param string $value
1271 * @param string $msg
1272 */
1273 private function assertEmpty2( $value, $msg ) {
1274 $this->assertTrue( $value == '', $msg );
1275 }
1276
1277 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1278 $tableName = substr( $tableName, strlen( $prefix ) );
1279 }
1280
1281 private static function isNotUnittest( $table ) {
1282 return strpos( $table, 'unittest_' ) !== 0;
1283 }
1284
1285 /**
1286 * @since 1.18
1287 *
1288 * @param DatabaseBase $db
1289 *
1290 * @return array
1291 */
1292 public static function listTables( $db ) {
1293 $prefix = $db->tablePrefix();
1294 $tables = $db->listTables( $prefix, __METHOD__ );
1295
1296 if ( $db->getType() === 'mysql' ) {
1297 # bug 43571: cannot clone VIEWs under MySQL
1298 $views = $db->listViews( $prefix, __METHOD__ );
1299 $tables = array_diff( $tables, $views );
1300 }
1301 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1302
1303 // Don't duplicate test tables from the previous fataled run
1304 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1305
1306 if ( $db->getType() == 'sqlite' ) {
1307 $tables = array_flip( $tables );
1308 // these are subtables of searchindex and don't need to be duped/dropped separately
1309 unset( $tables['searchindex_content'] );
1310 unset( $tables['searchindex_segdir'] );
1311 unset( $tables['searchindex_segments'] );
1312 $tables = array_flip( $tables );
1313 }
1314
1315 return $tables;
1316 }
1317
1318 /**
1319 * @throws MWException
1320 * @since 1.18
1321 */
1322 protected function checkDbIsSupported() {
1323 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1324 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1325 }
1326 }
1327
1328 /**
1329 * @since 1.18
1330 * @param string $offset
1331 * @return mixed
1332 */
1333 public function getCliArg( $offset ) {
1334 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1335 return PHPUnitMaintClass::$additionalOptions[$offset];
1336 }
1337 }
1338
1339 /**
1340 * @since 1.18
1341 * @param string $offset
1342 * @param mixed $value
1343 */
1344 public function setCliArg( $offset, $value ) {
1345 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1346 }
1347
1348 /**
1349 * Don't throw a warning if $function is deprecated and called later
1350 *
1351 * @since 1.19
1352 *
1353 * @param string $function
1354 */
1355 public function hideDeprecated( $function ) {
1356 MediaWiki\suppressWarnings();
1357 wfDeprecated( $function );
1358 MediaWiki\restoreWarnings();
1359 }
1360
1361 /**
1362 * Asserts that the given database query yields the rows given by $expectedRows.
1363 * The expected rows should be given as indexed (not associative) arrays, with
1364 * the values given in the order of the columns in the $fields parameter.
1365 * Note that the rows are sorted by the columns given in $fields.
1366 *
1367 * @since 1.20
1368 *
1369 * @param string|array $table The table(s) to query
1370 * @param string|array $fields The columns to include in the result (and to sort by)
1371 * @param string|array $condition "where" condition(s)
1372 * @param array $expectedRows An array of arrays giving the expected rows.
1373 *
1374 * @throws MWException If this test cases's needsDB() method doesn't return true.
1375 * Test cases can use "@group Database" to enable database test support,
1376 * or list the tables under testing in $this->tablesUsed, or override the
1377 * needsDB() method.
1378 */
1379 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1380 if ( !$this->needsDB() ) {
1381 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1382 ' method should return true. Use @group Database or $this->tablesUsed.' );
1383 }
1384
1385 $db = wfGetDB( DB_SLAVE );
1386
1387 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1388 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1389
1390 $i = 0;
1391
1392 foreach ( $expectedRows as $expected ) {
1393 $r = $res->fetchRow();
1394 self::stripStringKeys( $r );
1395
1396 $i += 1;
1397 $this->assertNotEmpty( $r, "row #$i missing" );
1398
1399 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1400 }
1401
1402 $r = $res->fetchRow();
1403 self::stripStringKeys( $r );
1404
1405 $this->assertFalse( $r, "found extra row (after #$i)" );
1406 }
1407
1408 /**
1409 * Utility method taking an array of elements and wrapping
1410 * each element in its own array. Useful for data providers
1411 * that only return a single argument.
1412 *
1413 * @since 1.20
1414 *
1415 * @param array $elements
1416 *
1417 * @return array
1418 */
1419 protected function arrayWrap( array $elements ) {
1420 return array_map(
1421 function ( $element ) {
1422 return [ $element ];
1423 },
1424 $elements
1425 );
1426 }
1427
1428 /**
1429 * Assert that two arrays are equal. By default this means that both arrays need to hold
1430 * the same set of values. Using additional arguments, order and associated key can also
1431 * be set as relevant.
1432 *
1433 * @since 1.20
1434 *
1435 * @param array $expected
1436 * @param array $actual
1437 * @param bool $ordered If the order of the values should match
1438 * @param bool $named If the keys should match
1439 */
1440 protected function assertArrayEquals( array $expected, array $actual,
1441 $ordered = false, $named = false
1442 ) {
1443 if ( !$ordered ) {
1444 $this->objectAssociativeSort( $expected );
1445 $this->objectAssociativeSort( $actual );
1446 }
1447
1448 if ( !$named ) {
1449 $expected = array_values( $expected );
1450 $actual = array_values( $actual );
1451 }
1452
1453 call_user_func_array(
1454 [ $this, 'assertEquals' ],
1455 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1456 );
1457 }
1458
1459 /**
1460 * Put each HTML element on its own line and then equals() the results
1461 *
1462 * Use for nicely formatting of PHPUnit diff output when comparing very
1463 * simple HTML
1464 *
1465 * @since 1.20
1466 *
1467 * @param string $expected HTML on oneline
1468 * @param string $actual HTML on oneline
1469 * @param string $msg Optional message
1470 */
1471 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1472 $expected = str_replace( '>', ">\n", $expected );
1473 $actual = str_replace( '>', ">\n", $actual );
1474
1475 $this->assertEquals( $expected, $actual, $msg );
1476 }
1477
1478 /**
1479 * Does an associative sort that works for objects.
1480 *
1481 * @since 1.20
1482 *
1483 * @param array $array
1484 */
1485 protected function objectAssociativeSort( array &$array ) {
1486 uasort(
1487 $array,
1488 function ( $a, $b ) {
1489 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1490 }
1491 );
1492 }
1493
1494 /**
1495 * Utility function for eliminating all string keys from an array.
1496 * Useful to turn a database result row as returned by fetchRow() into
1497 * a pure indexed array.
1498 *
1499 * @since 1.20
1500 *
1501 * @param mixed $r The array to remove string keys from.
1502 */
1503 protected static function stripStringKeys( &$r ) {
1504 if ( !is_array( $r ) ) {
1505 return;
1506 }
1507
1508 foreach ( $r as $k => $v ) {
1509 if ( is_string( $k ) ) {
1510 unset( $r[$k] );
1511 }
1512 }
1513 }
1514
1515 /**
1516 * Asserts that the provided variable is of the specified
1517 * internal type or equals the $value argument. This is useful
1518 * for testing return types of functions that return a certain
1519 * type or *value* when not set or on error.
1520 *
1521 * @since 1.20
1522 *
1523 * @param string $type
1524 * @param mixed $actual
1525 * @param mixed $value
1526 * @param string $message
1527 */
1528 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1529 if ( $actual === $value ) {
1530 $this->assertTrue( true, $message );
1531 } else {
1532 $this->assertType( $type, $actual, $message );
1533 }
1534 }
1535
1536 /**
1537 * Asserts the type of the provided value. This can be either
1538 * in internal type such as boolean or integer, or a class or
1539 * interface the value extends or implements.
1540 *
1541 * @since 1.20
1542 *
1543 * @param string $type
1544 * @param mixed $actual
1545 * @param string $message
1546 */
1547 protected function assertType( $type, $actual, $message = '' ) {
1548 if ( class_exists( $type ) || interface_exists( $type ) ) {
1549 $this->assertInstanceOf( $type, $actual, $message );
1550 } else {
1551 $this->assertInternalType( $type, $actual, $message );
1552 }
1553 }
1554
1555 /**
1556 * Returns true if the given namespace defaults to Wikitext
1557 * according to $wgNamespaceContentModels
1558 *
1559 * @param int $ns The namespace ID to check
1560 *
1561 * @return bool
1562 * @since 1.21
1563 */
1564 protected function isWikitextNS( $ns ) {
1565 global $wgNamespaceContentModels;
1566
1567 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1568 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1569 }
1570
1571 return true;
1572 }
1573
1574 /**
1575 * Returns the ID of a namespace that defaults to Wikitext.
1576 *
1577 * @throws MWException If there is none.
1578 * @return int The ID of the wikitext Namespace
1579 * @since 1.21
1580 */
1581 protected function getDefaultWikitextNS() {
1582 global $wgNamespaceContentModels;
1583
1584 static $wikitextNS = null; // this is not going to change
1585 if ( $wikitextNS !== null ) {
1586 return $wikitextNS;
1587 }
1588
1589 // quickly short out on most common case:
1590 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1591 return NS_MAIN;
1592 }
1593
1594 // NOTE: prefer content namespaces
1595 $namespaces = array_unique( array_merge(
1596 MWNamespace::getContentNamespaces(),
1597 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1598 MWNamespace::getValidNamespaces()
1599 ) );
1600
1601 $namespaces = array_diff( $namespaces, [
1602 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1603 ] );
1604
1605 $talk = array_filter( $namespaces, function ( $ns ) {
1606 return MWNamespace::isTalk( $ns );
1607 } );
1608
1609 // prefer non-talk pages
1610 $namespaces = array_diff( $namespaces, $talk );
1611 $namespaces = array_merge( $namespaces, $talk );
1612
1613 // check default content model of each namespace
1614 foreach ( $namespaces as $ns ) {
1615 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1616 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1617 ) {
1618
1619 $wikitextNS = $ns;
1620
1621 return $wikitextNS;
1622 }
1623 }
1624
1625 // give up
1626 // @todo Inside a test, we could skip the test as incomplete.
1627 // But frequently, this is used in fixture setup.
1628 throw new MWException( "No namespace defaults to wikitext!" );
1629 }
1630
1631 /**
1632 * Check, if $wgDiff3 is set and ready to merge
1633 * Will mark the calling test as skipped, if not ready
1634 *
1635 * @since 1.21
1636 */
1637 protected function markTestSkippedIfNoDiff3() {
1638 global $wgDiff3;
1639
1640 # This check may also protect against code injection in
1641 # case of broken installations.
1642 MediaWiki\suppressWarnings();
1643 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1644 MediaWiki\restoreWarnings();
1645
1646 if ( !$haveDiff3 ) {
1647 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1648 }
1649 }
1650
1651 /**
1652 * Check if $extName is a loaded PHP extension, will skip the
1653 * test whenever it is not loaded.
1654 *
1655 * @since 1.21
1656 * @param string $extName
1657 * @return bool
1658 */
1659 protected function checkPHPExtension( $extName ) {
1660 $loaded = extension_loaded( $extName );
1661 if ( !$loaded ) {
1662 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1663 }
1664
1665 return $loaded;
1666 }
1667
1668 /**
1669 * Asserts that the given string is a valid HTML snippet.
1670 * Wraps the given string in the required top level tags and
1671 * then calls assertValidHtmlDocument().
1672 * The snippet is expected to be HTML 5.
1673 *
1674 * @since 1.23
1675 *
1676 * @note Will mark the test as skipped if the "tidy" module is not installed.
1677 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1678 * when automatic tidying is disabled.
1679 *
1680 * @param string $html An HTML snippet (treated as the contents of the body tag).
1681 */
1682 protected function assertValidHtmlSnippet( $html ) {
1683 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1684 $this->assertValidHtmlDocument( $html );
1685 }
1686
1687 /**
1688 * Asserts that the given string is valid HTML document.
1689 *
1690 * @since 1.23
1691 *
1692 * @note Will mark the test as skipped if the "tidy" module is not installed.
1693 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1694 * when automatic tidying is disabled.
1695 *
1696 * @param string $html A complete HTML document
1697 */
1698 protected function assertValidHtmlDocument( $html ) {
1699 // Note: we only validate if the tidy PHP extension is available.
1700 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1701 // of tidy. In that case however, we can not reliably detect whether a failing validation
1702 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1703 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1704 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1705 $this->markTestSkipped( 'Tidy extension not installed' );
1706 }
1707
1708 $errorBuffer = '';
1709 MWTidy::checkErrors( $html, $errorBuffer );
1710 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1711
1712 // Filter Tidy warnings which aren't useful for us.
1713 // Tidy eg. often cries about parameters missing which have actually
1714 // been deprecated since HTML4, thus we should not care about them.
1715 $errors = preg_grep(
1716 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1717 $allErrors, PREG_GREP_INVERT
1718 );
1719
1720 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1721 }
1722
1723 /**
1724 * @param array $matcher
1725 * @param string $actual
1726 * @param bool $isHtml
1727 *
1728 * @return bool
1729 */
1730 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1731 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1732 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1733 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1734 }
1735
1736 /**
1737 * Note: we are overriding this method to remove the deprecated error
1738 * @see https://phabricator.wikimedia.org/T71505
1739 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1740 * @deprecated
1741 *
1742 * @param array $matcher
1743 * @param string $actual
1744 * @param string $message
1745 * @param bool $isHtml
1746 */
1747 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1748 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1749
1750 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1751 }
1752
1753 /**
1754 * @see MediaWikiTestCase::assertTag
1755 * @deprecated
1756 *
1757 * @param array $matcher
1758 * @param string $actual
1759 * @param string $message
1760 * @param bool $isHtml
1761 */
1762 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1763 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1764
1765 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1766 }
1767
1768 /**
1769 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1770 * @return string
1771 */
1772 public static function wfResetOutputBuffersBarrier( $buffer ) {
1773 return $buffer;
1774 }
1775
1776 /**
1777 * Create a temporary hook handler which will be reset by tearDown.
1778 * This replaces other handlers for the same hook.
1779 * @param string $hookName Hook name
1780 * @param mixed $handler Value suitable for a hook handler
1781 * @since 1.28
1782 */
1783 protected function setTemporaryHook( $hookName, $handler ) {
1784 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
1785 }
1786
1787 }