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