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