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