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