Allow reset of global services (redux).
[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
502 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
503
504 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
505 ini_set( 'error_reporting', $this->phpErrorLevel );
506
507 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
508 $newHex = strtoupper( dechex( $phpErrorLevel ) );
509 $message = "PHP error_reporting setting was left dirty: "
510 . "was 0x$oldHex before test, 0x$newHex after test!";
511
512 $this->fail( $message );
513 }
514
515 parent::tearDown();
516 }
517
518 /**
519 * Make sure MediaWikiTestCase extending classes have called their
520 * parent setUp method
521 */
522 final public function testMediaWikiTestCaseParentSetupCalled() {
523 $this->assertArrayHasKey( 'setUp', $this->called,
524 static::class . '::setUp() must call parent::setUp()'
525 );
526 }
527
528 /**
529 * Sets a service, maintaining a stashed version of the previous service to be
530 * restored in tearDown
531 *
532 * @since 1.27
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 $user->addGroup( 'sysop' );
929 $user->addGroup( 'bureaucrat' );
930 }
931
932 // Make 1 page with 1 revision
933 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
934 if ( $page->getId() == 0 ) {
935 $page->doEditContent(
936 new WikitextContent( 'UTContent' ),
937 'UTPageSummary',
938 EDIT_NEW,
939 false,
940 $user
941 );
942
943 // doEditContent() probably started the session via
944 // User::loadFromSession(). Close it now.
945 if ( session_id() !== '' ) {
946 session_write_close();
947 session_id( '' );
948 }
949 }
950 }
951
952 /**
953 * Restores MediaWiki to using the table set (table prefix) it was using before
954 * setupTestDB() was called. Useful if we need to perform database operations
955 * after the test run has finished (such as saving logs or profiling info).
956 *
957 * @since 1.21
958 */
959 public static function teardownTestDB() {
960 global $wgJobClasses;
961
962 if ( !self::$dbSetup ) {
963 return;
964 }
965
966 foreach ( $wgJobClasses as $type => $class ) {
967 // Delete any jobs under the clone DB (or old prefix in other stores)
968 JobQueueGroup::singleton()->get( $type )->delete();
969 }
970
971 CloneDatabase::changePrefix( self::$oldTablePrefix );
972
973 self::$oldTablePrefix = false;
974 self::$dbSetup = false;
975 }
976
977 /**
978 * Setups a database with the given prefix.
979 *
980 * If reuseDB is true and certain conditions apply, it will just change the prefix.
981 * Otherwise, it will clone the tables and change the prefix.
982 *
983 * Clones all tables in the given database (whatever database that connection has
984 * open), to versions with the test prefix.
985 *
986 * @param DatabaseBase $db Database to use
987 * @param string $prefix Prefix to use for test tables
988 * @return bool True if tables were cloned, false if only the prefix was changed
989 */
990 protected static function setupDatabaseWithTestPrefix( DatabaseBase $db, $prefix ) {
991 $tablesCloned = self::listTables( $db );
992 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
993 $dbClone->useTemporaryTables( self::$useTemporaryTables );
994
995 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
996 CloneDatabase::changePrefix( $prefix );
997
998 return false;
999 } else {
1000 $dbClone->cloneTableStructure();
1001 return true;
1002 }
1003 }
1004
1005 /**
1006 * Set up all test DBs
1007 */
1008 public function setupAllTestDBs() {
1009 global $wgDBprefix;
1010
1011 self::$oldTablePrefix = $wgDBprefix;
1012
1013 $testPrefix = $this->dbPrefix();
1014
1015 // switch to a temporary clone of the database
1016 self::setupTestDB( $this->db, $testPrefix );
1017
1018 if ( self::isUsingExternalStoreDB() ) {
1019 self::setupExternalStoreTestDBs( $testPrefix );
1020 }
1021 }
1022
1023 /**
1024 * Creates an empty skeleton of the wiki database by cloning its structure
1025 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1026 * use the new set of tables (aka schema) instead of the original set.
1027 *
1028 * This is used to generate a dummy table set, typically consisting of temporary
1029 * tables, that will be used by tests instead of the original wiki database tables.
1030 *
1031 * @since 1.21
1032 *
1033 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1034 * by teardownTestDB() to return the wiki to using the original table set.
1035 *
1036 * @note this method only works when first called. Subsequent calls have no effect,
1037 * even if using different parameters.
1038 *
1039 * @param DatabaseBase $db The database connection
1040 * @param string $prefix The prefix to use for the new table set (aka schema).
1041 *
1042 * @throws MWException If the database table prefix is already $prefix
1043 */
1044 public static function setupTestDB( DatabaseBase $db, $prefix ) {
1045 if ( $db->tablePrefix() === $prefix ) {
1046 throw new MWException(
1047 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1048 }
1049
1050 if ( self::$dbSetup ) {
1051 return;
1052 }
1053
1054 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1055 // and DatabaseBase no longer use global state.
1056
1057 self::$dbSetup = true;
1058
1059 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1060 return;
1061 }
1062
1063 // Assuming this isn't needed for External Store database, and not sure if the procedure
1064 // would be available there.
1065 if ( $db->getType() == 'oracle' ) {
1066 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1067 }
1068 }
1069
1070 /**
1071 * Clones the External Store database(s) for testing
1072 *
1073 * @param string $testPrefix Prefix for test tables
1074 */
1075 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1076 $connections = self::getExternalStoreDatabaseConnections();
1077 foreach ( $connections as $dbw ) {
1078 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1079 // prefix,. Even though listTables now uses tablePrefix, that
1080 // itself is populated from $wgDBprefix by default.
1081
1082 // We have to set it back, or we won't find the original 'blobs'
1083 // table to copy.
1084
1085 $dbw->tablePrefix( self::$oldTablePrefix );
1086 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1087 }
1088 }
1089
1090 /**
1091 * Gets master database connections for all of the ExternalStoreDB
1092 * stores configured in $wgDefaultExternalStore.
1093 *
1094 * @return array Array of DatabaseBase master connections
1095 */
1096
1097 protected static function getExternalStoreDatabaseConnections() {
1098 global $wgDefaultExternalStore;
1099
1100 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1101 $defaultArray = (array) $wgDefaultExternalStore;
1102 $dbws = [];
1103 foreach ( $defaultArray as $url ) {
1104 if ( strpos( $url, 'DB://' ) === 0 ) {
1105 list( $proto, $cluster ) = explode( '://', $url, 2 );
1106 $dbw = $externalStoreDB->getMaster( $cluster );
1107 $dbws[] = $dbw;
1108 }
1109 }
1110
1111 return $dbws;
1112 }
1113
1114 /**
1115 * Check whether ExternalStoreDB is being used
1116 *
1117 * @return bool True if it's being used
1118 */
1119 protected static function isUsingExternalStoreDB() {
1120 global $wgDefaultExternalStore;
1121 if ( !$wgDefaultExternalStore ) {
1122 return false;
1123 }
1124
1125 $defaultArray = (array) $wgDefaultExternalStore;
1126 foreach ( $defaultArray as $url ) {
1127 if ( strpos( $url, 'DB://' ) === 0 ) {
1128 return true;
1129 }
1130 }
1131
1132 return false;
1133 }
1134
1135 /**
1136 * Empty all tables so they can be repopulated for tests
1137 *
1138 * @param DatabaseBase $db|null Database to reset
1139 * @param array $tablesUsed Tables to reset
1140 */
1141 private function resetDB( $db, $tablesUsed ) {
1142 if ( $db ) {
1143 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1144 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1145
1146 // If any of the user tables were marked as used, we should clear all of them.
1147 if ( array_intersect( $tablesUsed, $userTables ) ) {
1148 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1149
1150 // Totally clear User class in-process cache to avoid CAS errors
1151 TestingAccessWrapper::newFromClass( 'User' )
1152 ->getInProcessCache()
1153 ->clear();
1154 }
1155
1156 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1157 foreach ( $tablesUsed as $tbl ) {
1158 // TODO: reset interwiki table to its original content.
1159 if ( $tbl == 'interwiki' ) {
1160 continue;
1161 }
1162
1163 if ( $truncate ) {
1164 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1165 } else {
1166 $db->delete( $tbl, '*', __METHOD__ );
1167 }
1168
1169 if ( $tbl === 'page' ) {
1170 // Forget about the pages since they don't
1171 // exist in the DB.
1172 LinkCache::singleton()->clear();
1173 }
1174 }
1175
1176 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1177 // Re-add core DB data that was deleted
1178 $this->addCoreDBData();
1179 }
1180 }
1181 }
1182
1183 /**
1184 * @since 1.18
1185 *
1186 * @param string $func
1187 * @param array $args
1188 *
1189 * @return mixed
1190 * @throws MWException
1191 */
1192 public function __call( $func, $args ) {
1193 static $compatibility = [
1194 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1195 ];
1196
1197 if ( isset( $compatibility[$func] ) ) {
1198 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1199 } else {
1200 throw new MWException( "Called non-existent $func method on "
1201 . get_class( $this ) );
1202 }
1203 }
1204
1205 /**
1206 * Used as a compatibility method for phpunit < 3.7.32
1207 * @param string $value
1208 * @param string $msg
1209 */
1210 private function assertEmpty2( $value, $msg ) {
1211 $this->assertTrue( $value == '', $msg );
1212 }
1213
1214 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1215 $tableName = substr( $tableName, strlen( $prefix ) );
1216 }
1217
1218 private static function isNotUnittest( $table ) {
1219 return strpos( $table, 'unittest_' ) !== 0;
1220 }
1221
1222 /**
1223 * @since 1.18
1224 *
1225 * @param DatabaseBase $db
1226 *
1227 * @return array
1228 */
1229 public static function listTables( $db ) {
1230 $prefix = $db->tablePrefix();
1231 $tables = $db->listTables( $prefix, __METHOD__ );
1232
1233 if ( $db->getType() === 'mysql' ) {
1234 # bug 43571: cannot clone VIEWs under MySQL
1235 $views = $db->listViews( $prefix, __METHOD__ );
1236 $tables = array_diff( $tables, $views );
1237 }
1238 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1239
1240 // Don't duplicate test tables from the previous fataled run
1241 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1242
1243 if ( $db->getType() == 'sqlite' ) {
1244 $tables = array_flip( $tables );
1245 // these are subtables of searchindex and don't need to be duped/dropped separately
1246 unset( $tables['searchindex_content'] );
1247 unset( $tables['searchindex_segdir'] );
1248 unset( $tables['searchindex_segments'] );
1249 $tables = array_flip( $tables );
1250 }
1251
1252 return $tables;
1253 }
1254
1255 /**
1256 * @throws MWException
1257 * @since 1.18
1258 */
1259 protected function checkDbIsSupported() {
1260 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1261 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1262 }
1263 }
1264
1265 /**
1266 * @since 1.18
1267 * @param string $offset
1268 * @return mixed
1269 */
1270 public function getCliArg( $offset ) {
1271 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1272 return PHPUnitMaintClass::$additionalOptions[$offset];
1273 }
1274 }
1275
1276 /**
1277 * @since 1.18
1278 * @param string $offset
1279 * @param mixed $value
1280 */
1281 public function setCliArg( $offset, $value ) {
1282 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1283 }
1284
1285 /**
1286 * Don't throw a warning if $function is deprecated and called later
1287 *
1288 * @since 1.19
1289 *
1290 * @param string $function
1291 */
1292 public function hideDeprecated( $function ) {
1293 MediaWiki\suppressWarnings();
1294 wfDeprecated( $function );
1295 MediaWiki\restoreWarnings();
1296 }
1297
1298 /**
1299 * Asserts that the given database query yields the rows given by $expectedRows.
1300 * The expected rows should be given as indexed (not associative) arrays, with
1301 * the values given in the order of the columns in the $fields parameter.
1302 * Note that the rows are sorted by the columns given in $fields.
1303 *
1304 * @since 1.20
1305 *
1306 * @param string|array $table The table(s) to query
1307 * @param string|array $fields The columns to include in the result (and to sort by)
1308 * @param string|array $condition "where" condition(s)
1309 * @param array $expectedRows An array of arrays giving the expected rows.
1310 *
1311 * @throws MWException If this test cases's needsDB() method doesn't return true.
1312 * Test cases can use "@group Database" to enable database test support,
1313 * or list the tables under testing in $this->tablesUsed, or override the
1314 * needsDB() method.
1315 */
1316 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1317 if ( !$this->needsDB() ) {
1318 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1319 ' method should return true. Use @group Database or $this->tablesUsed.' );
1320 }
1321
1322 $db = wfGetDB( DB_SLAVE );
1323
1324 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1325 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1326
1327 $i = 0;
1328
1329 foreach ( $expectedRows as $expected ) {
1330 $r = $res->fetchRow();
1331 self::stripStringKeys( $r );
1332
1333 $i += 1;
1334 $this->assertNotEmpty( $r, "row #$i missing" );
1335
1336 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1337 }
1338
1339 $r = $res->fetchRow();
1340 self::stripStringKeys( $r );
1341
1342 $this->assertFalse( $r, "found extra row (after #$i)" );
1343 }
1344
1345 /**
1346 * Utility method taking an array of elements and wrapping
1347 * each element in its own array. Useful for data providers
1348 * that only return a single argument.
1349 *
1350 * @since 1.20
1351 *
1352 * @param array $elements
1353 *
1354 * @return array
1355 */
1356 protected function arrayWrap( array $elements ) {
1357 return array_map(
1358 function ( $element ) {
1359 return [ $element ];
1360 },
1361 $elements
1362 );
1363 }
1364
1365 /**
1366 * Assert that two arrays are equal. By default this means that both arrays need to hold
1367 * the same set of values. Using additional arguments, order and associated key can also
1368 * be set as relevant.
1369 *
1370 * @since 1.20
1371 *
1372 * @param array $expected
1373 * @param array $actual
1374 * @param bool $ordered If the order of the values should match
1375 * @param bool $named If the keys should match
1376 */
1377 protected function assertArrayEquals( array $expected, array $actual,
1378 $ordered = false, $named = false
1379 ) {
1380 if ( !$ordered ) {
1381 $this->objectAssociativeSort( $expected );
1382 $this->objectAssociativeSort( $actual );
1383 }
1384
1385 if ( !$named ) {
1386 $expected = array_values( $expected );
1387 $actual = array_values( $actual );
1388 }
1389
1390 call_user_func_array(
1391 [ $this, 'assertEquals' ],
1392 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1393 );
1394 }
1395
1396 /**
1397 * Put each HTML element on its own line and then equals() the results
1398 *
1399 * Use for nicely formatting of PHPUnit diff output when comparing very
1400 * simple HTML
1401 *
1402 * @since 1.20
1403 *
1404 * @param string $expected HTML on oneline
1405 * @param string $actual HTML on oneline
1406 * @param string $msg Optional message
1407 */
1408 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1409 $expected = str_replace( '>', ">\n", $expected );
1410 $actual = str_replace( '>', ">\n", $actual );
1411
1412 $this->assertEquals( $expected, $actual, $msg );
1413 }
1414
1415 /**
1416 * Does an associative sort that works for objects.
1417 *
1418 * @since 1.20
1419 *
1420 * @param array $array
1421 */
1422 protected function objectAssociativeSort( array &$array ) {
1423 uasort(
1424 $array,
1425 function ( $a, $b ) {
1426 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1427 }
1428 );
1429 }
1430
1431 /**
1432 * Utility function for eliminating all string keys from an array.
1433 * Useful to turn a database result row as returned by fetchRow() into
1434 * a pure indexed array.
1435 *
1436 * @since 1.20
1437 *
1438 * @param mixed $r The array to remove string keys from.
1439 */
1440 protected static function stripStringKeys( &$r ) {
1441 if ( !is_array( $r ) ) {
1442 return;
1443 }
1444
1445 foreach ( $r as $k => $v ) {
1446 if ( is_string( $k ) ) {
1447 unset( $r[$k] );
1448 }
1449 }
1450 }
1451
1452 /**
1453 * Asserts that the provided variable is of the specified
1454 * internal type or equals the $value argument. This is useful
1455 * for testing return types of functions that return a certain
1456 * type or *value* when not set or on error.
1457 *
1458 * @since 1.20
1459 *
1460 * @param string $type
1461 * @param mixed $actual
1462 * @param mixed $value
1463 * @param string $message
1464 */
1465 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1466 if ( $actual === $value ) {
1467 $this->assertTrue( true, $message );
1468 } else {
1469 $this->assertType( $type, $actual, $message );
1470 }
1471 }
1472
1473 /**
1474 * Asserts the type of the provided value. This can be either
1475 * in internal type such as boolean or integer, or a class or
1476 * interface the value extends or implements.
1477 *
1478 * @since 1.20
1479 *
1480 * @param string $type
1481 * @param mixed $actual
1482 * @param string $message
1483 */
1484 protected function assertType( $type, $actual, $message = '' ) {
1485 if ( class_exists( $type ) || interface_exists( $type ) ) {
1486 $this->assertInstanceOf( $type, $actual, $message );
1487 } else {
1488 $this->assertInternalType( $type, $actual, $message );
1489 }
1490 }
1491
1492 /**
1493 * Returns true if the given namespace defaults to Wikitext
1494 * according to $wgNamespaceContentModels
1495 *
1496 * @param int $ns The namespace ID to check
1497 *
1498 * @return bool
1499 * @since 1.21
1500 */
1501 protected function isWikitextNS( $ns ) {
1502 global $wgNamespaceContentModels;
1503
1504 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1505 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1506 }
1507
1508 return true;
1509 }
1510
1511 /**
1512 * Returns the ID of a namespace that defaults to Wikitext.
1513 *
1514 * @throws MWException If there is none.
1515 * @return int The ID of the wikitext Namespace
1516 * @since 1.21
1517 */
1518 protected function getDefaultWikitextNS() {
1519 global $wgNamespaceContentModels;
1520
1521 static $wikitextNS = null; // this is not going to change
1522 if ( $wikitextNS !== null ) {
1523 return $wikitextNS;
1524 }
1525
1526 // quickly short out on most common case:
1527 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1528 return NS_MAIN;
1529 }
1530
1531 // NOTE: prefer content namespaces
1532 $namespaces = array_unique( array_merge(
1533 MWNamespace::getContentNamespaces(),
1534 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1535 MWNamespace::getValidNamespaces()
1536 ) );
1537
1538 $namespaces = array_diff( $namespaces, [
1539 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1540 ] );
1541
1542 $talk = array_filter( $namespaces, function ( $ns ) {
1543 return MWNamespace::isTalk( $ns );
1544 } );
1545
1546 // prefer non-talk pages
1547 $namespaces = array_diff( $namespaces, $talk );
1548 $namespaces = array_merge( $namespaces, $talk );
1549
1550 // check default content model of each namespace
1551 foreach ( $namespaces as $ns ) {
1552 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1553 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1554 ) {
1555
1556 $wikitextNS = $ns;
1557
1558 return $wikitextNS;
1559 }
1560 }
1561
1562 // give up
1563 // @todo Inside a test, we could skip the test as incomplete.
1564 // But frequently, this is used in fixture setup.
1565 throw new MWException( "No namespace defaults to wikitext!" );
1566 }
1567
1568 /**
1569 * Check, if $wgDiff3 is set and ready to merge
1570 * Will mark the calling test as skipped, if not ready
1571 *
1572 * @since 1.21
1573 */
1574 protected function markTestSkippedIfNoDiff3() {
1575 global $wgDiff3;
1576
1577 # This check may also protect against code injection in
1578 # case of broken installations.
1579 MediaWiki\suppressWarnings();
1580 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1581 MediaWiki\restoreWarnings();
1582
1583 if ( !$haveDiff3 ) {
1584 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1585 }
1586 }
1587
1588 /**
1589 * Check whether we have the 'gzip' commandline utility, will skip
1590 * the test whenever "gzip -V" fails.
1591 *
1592 * Result is cached at the process level.
1593 *
1594 * @return bool
1595 *
1596 * @since 1.21
1597 */
1598 protected function checkHasGzip() {
1599 static $haveGzip;
1600
1601 if ( $haveGzip === null ) {
1602 $retval = null;
1603 wfShellExec( 'gzip -V', $retval );
1604 $haveGzip = ( $retval === 0 );
1605 }
1606
1607 if ( !$haveGzip ) {
1608 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1609 }
1610
1611 return $haveGzip;
1612 }
1613
1614 /**
1615 * Check if $extName is a loaded PHP extension, will skip the
1616 * test whenever it is not loaded.
1617 *
1618 * @since 1.21
1619 * @param string $extName
1620 * @return bool
1621 */
1622 protected function checkPHPExtension( $extName ) {
1623 $loaded = extension_loaded( $extName );
1624 if ( !$loaded ) {
1625 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1626 }
1627
1628 return $loaded;
1629 }
1630
1631 /**
1632 * Asserts that the given string is a valid HTML snippet.
1633 * Wraps the given string in the required top level tags and
1634 * then calls assertValidHtmlDocument().
1635 * The snippet is expected to be HTML 5.
1636 *
1637 * @since 1.23
1638 *
1639 * @note Will mark the test as skipped if the "tidy" module is not installed.
1640 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1641 * when automatic tidying is disabled.
1642 *
1643 * @param string $html An HTML snippet (treated as the contents of the body tag).
1644 */
1645 protected function assertValidHtmlSnippet( $html ) {
1646 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1647 $this->assertValidHtmlDocument( $html );
1648 }
1649
1650 /**
1651 * Asserts that the given string is valid HTML document.
1652 *
1653 * @since 1.23
1654 *
1655 * @note Will mark the test as skipped if the "tidy" module is not installed.
1656 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1657 * when automatic tidying is disabled.
1658 *
1659 * @param string $html A complete HTML document
1660 */
1661 protected function assertValidHtmlDocument( $html ) {
1662 // Note: we only validate if the tidy PHP extension is available.
1663 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1664 // of tidy. In that case however, we can not reliably detect whether a failing validation
1665 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1666 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1667 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1668 $this->markTestSkipped( 'Tidy extension not installed' );
1669 }
1670
1671 $errorBuffer = '';
1672 MWTidy::checkErrors( $html, $errorBuffer );
1673 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1674
1675 // Filter Tidy warnings which aren't useful for us.
1676 // Tidy eg. often cries about parameters missing which have actually
1677 // been deprecated since HTML4, thus we should not care about them.
1678 $errors = preg_grep(
1679 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1680 $allErrors, PREG_GREP_INVERT
1681 );
1682
1683 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1684 }
1685
1686 /**
1687 * @param array $matcher
1688 * @param string $actual
1689 * @param bool $isHtml
1690 *
1691 * @return bool
1692 */
1693 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1694 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1695 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1696 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1697 }
1698
1699 /**
1700 * Note: we are overriding this method to remove the deprecated error
1701 * @see https://phabricator.wikimedia.org/T71505
1702 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1703 * @deprecated
1704 *
1705 * @param array $matcher
1706 * @param string $actual
1707 * @param string $message
1708 * @param bool $isHtml
1709 */
1710 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1711 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1712
1713 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1714 }
1715
1716 /**
1717 * @see MediaWikiTestCase::assertTag
1718 * @deprecated
1719 *
1720 * @param array $matcher
1721 * @param string $actual
1722 * @param string $message
1723 * @param bool $isHtml
1724 */
1725 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1726 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1727
1728 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1729 }
1730
1731 /**
1732 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1733 * @return string
1734 */
1735 public static function wfResetOutputBuffersBarrier( $buffer ) {
1736 return $buffer;
1737 }
1738
1739 }