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