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