Replace $wgUser with RequestContext::getUser in User::getBlockedStatus
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 use MediaWiki\Logger\LegacySpi;
4 use MediaWiki\Logger\LoggerFactory;
5 use MediaWiki\Logger\MonologSpi;
6 use MediaWiki\Logger\LogCapturingSpi;
7 use MediaWiki\MediaWikiServices;
8 use Psr\Log\LoggerInterface;
9 use Wikimedia\Rdbms\IDatabase;
10 use Wikimedia\Rdbms\IMaintainableDatabase;
11 use Wikimedia\Rdbms\Database;
12 use Wikimedia\TestingAccessWrapper;
13
14 /**
15 * @since 1.18
16 */
17 abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase {
18
19 use MediaWikiCoversValidator;
20 use PHPUnit4And6Compat;
21
22 /**
23 * The original service locator. This is overridden during setUp().
24 *
25 * @var MediaWikiServices|null
26 */
27 private static $originalServices;
28
29 /**
30 * The local service locator, created during setUp().
31 * @var MediaWikiServices
32 */
33 private $localServices;
34
35 /**
36 * $called tracks whether the setUp and tearDown method has been called.
37 * class extending MediaWikiTestCase usually override setUp and tearDown
38 * but forget to call the parent.
39 *
40 * The array format takes a method name as key and anything as a value.
41 * By asserting the key exist, we know the child class has called the
42 * parent.
43 *
44 * This property must be private, we do not want child to override it,
45 * they should call the appropriate parent method instead.
46 */
47 private $called = [];
48
49 /**
50 * @var TestUser[]
51 * @since 1.20
52 */
53 public static $users;
54
55 /**
56 * Primary database
57 *
58 * @var Database
59 * @since 1.18
60 */
61 protected $db;
62
63 /**
64 * @var array
65 * @since 1.19
66 */
67 protected $tablesUsed = []; // tables with data
68
69 private static $useTemporaryTables = true;
70 private static $reuseDB = false;
71 private static $dbSetup = false;
72 private static $oldTablePrefix = '';
73
74 /**
75 * Original value of PHP's error_reporting setting.
76 *
77 * @var int
78 */
79 private $phpErrorLevel;
80
81 /**
82 * Holds the paths of temporary files/directories created through getNewTempFile,
83 * and getNewTempDirectory
84 *
85 * @var array
86 */
87 private $tmpFiles = [];
88
89 /**
90 * Holds original values of MediaWiki configuration settings
91 * to be restored in tearDown().
92 * See also setMwGlobals().
93 * @var array
94 */
95 private $mwGlobals = [];
96
97 /**
98 * Holds list of MediaWiki configuration settings to be unset in tearDown().
99 * See also setMwGlobals().
100 * @var array
101 */
102 private $mwGlobalsToUnset = [];
103
104 /**
105 * Holds original values of ini settings to be restored
106 * in tearDown().
107 * @see setIniSettings()
108 * @var array
109 */
110 private $iniSettings = [];
111
112 /**
113 * Holds original loggers which have been replaced by setLogger()
114 * @var LoggerInterface[]
115 */
116 private $loggers = [];
117
118 /**
119 * The CLI arguments passed through from phpunit.php
120 * @var array
121 */
122 private $cliArgs = [];
123
124 /**
125 * Holds a list of services that were overridden with setService(). Used for printing an error
126 * if overrideMwServices() overrides a service that was previously set.
127 * @var string[]
128 */
129 private $overriddenServices = [];
130
131 /**
132 * Table name prefixes. Oracle likes it shorter.
133 */
134 const DB_PREFIX = 'unittest_';
135 const ORA_DB_PREFIX = 'ut_';
136
137 /**
138 * @var array
139 * @since 1.18
140 */
141 protected $supportedDBs = [
142 'mysql',
143 'sqlite',
144 'postgres',
145 'oracle'
146 ];
147
148 public function __construct( $name = null, array $data = [], $dataName = '' ) {
149 parent::__construct( $name, $data, $dataName );
150
151 $this->backupGlobals = false;
152 $this->backupStaticAttributes = false;
153 }
154
155 public function __destruct() {
156 // Complain if self::setUp() was called, but not self::tearDown()
157 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
158 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
159 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
160 }
161 }
162
163 public static function setUpBeforeClass() {
164 parent::setUpBeforeClass();
165
166 // Get the original service locator
167 if ( !self::$originalServices ) {
168 self::$originalServices = MediaWikiServices::getInstance();
169 }
170 }
171
172 /**
173 * Convenience method for getting an immutable test user
174 *
175 * @since 1.28
176 *
177 * @param string|string[] $groups Groups the test user should be in.
178 * @return TestUser
179 */
180 public static function getTestUser( $groups = [] ) {
181 return TestUserRegistry::getImmutableTestUser( $groups );
182 }
183
184 /**
185 * Convenience method for getting a mutable test user
186 *
187 * @since 1.28
188 *
189 * @param string|string[] $groups Groups the test user should be added in.
190 * @return TestUser
191 */
192 public static function getMutableTestUser( $groups = [] ) {
193 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
194 }
195
196 /**
197 * Convenience method for getting an immutable admin test user
198 *
199 * @since 1.28
200 *
201 * @param string[] $groups Groups the test user should be added to.
202 * @return TestUser
203 */
204 public static function getTestSysop() {
205 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
206 }
207
208 /**
209 * Returns a WikiPage representing an existing page.
210 *
211 * @since 1.32
212 *
213 * @param Title|string|null $title
214 * @return WikiPage
215 * @throws MWException If this test cases's needsDB() method doesn't return true.
216 * Test cases can use "@group Database" to enable database test support,
217 * or list the tables under testing in $this->tablesUsed, or override the
218 * needsDB() method.
219 */
220 protected function getExistingTestPage( $title = null ) {
221 if ( !$this->needsDB() ) {
222 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
223 ' method should return true. Use @group Database or $this->tablesUsed.' );
224 }
225
226 $title = ( $title === null ) ? 'UTPage' : $title;
227 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
228 $page = WikiPage::factory( $title );
229
230 if ( !$page->exists() ) {
231 $user = self::getTestSysop()->getUser();
232 $page->doEditContent(
233 new WikitextContent( 'UTContent' ),
234 'UTPageSummary',
235 EDIT_NEW | EDIT_SUPPRESS_RC,
236 false,
237 $user
238 );
239 }
240
241 return $page;
242 }
243
244 /**
245 * Returns a WikiPage representing a non-existing page.
246 *
247 * @since 1.32
248 *
249 * @param Title|string|null $title
250 * @return WikiPage
251 * @throws MWException If this test cases's needsDB() method doesn't return true.
252 * Test cases can use "@group Database" to enable database test support,
253 * or list the tables under testing in $this->tablesUsed, or override the
254 * needsDB() method.
255 */
256 protected function getNonexistingTestPage( $title = null ) {
257 if ( !$this->needsDB() ) {
258 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
259 ' method should return true. Use @group Database or $this->tablesUsed.' );
260 }
261
262 $title = ( $title === null ) ? 'UTPage-' . rand( 0, 100000 ) : $title;
263 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
264 $page = WikiPage::factory( $title );
265
266 if ( $page->exists() ) {
267 $page->doDeleteArticle( 'Testing' );
268 }
269
270 return $page;
271 }
272
273 /**
274 * @deprecated since 1.32
275 */
276 public static function prepareServices( Config $bootstrapConfig ) {
277 }
278
279 /**
280 * Create a config suitable for testing, based on a base config, default overrides,
281 * and custom overrides.
282 *
283 * @param Config|null $baseConfig
284 * @param Config|null $customOverrides
285 *
286 * @return Config
287 */
288 private static function makeTestConfig(
289 Config $baseConfig = null,
290 Config $customOverrides = null
291 ) {
292 $defaultOverrides = new HashConfig();
293
294 if ( !$baseConfig ) {
295 $baseConfig = self::$originalServices->getBootstrapConfig();
296 }
297
298 /* Some functions require some kind of caching, and will end up using the db,
299 * which we can't allow, as that would open a new connection for mysql.
300 * Replace with a HashBag. They would not be going to persist anyway.
301 */
302 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
303 $objectCaches = [
304 CACHE_DB => $hashCache,
305 CACHE_ACCEL => $hashCache,
306 CACHE_MEMCACHED => $hashCache,
307 'apc' => $hashCache,
308 'apcu' => $hashCache,
309 'wincache' => $hashCache,
310 ] + $baseConfig->get( 'ObjectCaches' );
311
312 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
313 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
314 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory::class ] ] );
315
316 // Use a fast hash algorithm to hash passwords.
317 $defaultOverrides->set( 'PasswordDefault', 'A' );
318
319 $testConfig = $customOverrides
320 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
321 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
322
323 return $testConfig;
324 }
325
326 /**
327 * @param ConfigFactory $oldFactory
328 * @param Config[] $configurations
329 *
330 * @return Closure
331 */
332 private static function makeTestConfigFactoryInstantiator(
333 ConfigFactory $oldFactory,
334 array $configurations
335 ) {
336 return function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
337 $factory = new ConfigFactory();
338
339 // clone configurations from $oldFactory that are not overwritten by $configurations
340 $namesToClone = array_diff(
341 $oldFactory->getConfigNames(),
342 array_keys( $configurations )
343 );
344
345 foreach ( $namesToClone as $name ) {
346 $factory->register( $name, $oldFactory->makeConfig( $name ) );
347 }
348
349 foreach ( $configurations as $name => $config ) {
350 $factory->register( $name, $config );
351 }
352
353 return $factory;
354 };
355 }
356
357 /**
358 * Resets some non-service singleton instances and other static caches. It's not necessary to
359 * reset services here.
360 */
361 public static function resetNonServiceCaches() {
362 global $wgRequest, $wgJobClasses;
363
364 foreach ( $wgJobClasses as $type => $class ) {
365 JobQueueGroup::singleton()->get( $type )->delete();
366 }
367 JobQueueGroup::destroySingletons();
368
369 ObjectCache::clear();
370 FileBackendGroup::destroySingleton();
371 DeferredUpdates::clearPendingUpdates();
372
373 // TODO: move global state into MediaWikiServices
374 RequestContext::resetMain();
375 if ( session_id() !== '' ) {
376 session_write_close();
377 session_id( '' );
378 }
379
380 $wgRequest = new FauxRequest();
381 MediaWiki\Session\SessionManager::resetCache();
382 }
383
384 public function run( PHPUnit_Framework_TestResult $result = null ) {
385 if ( $result instanceof MediaWikiTestResult ) {
386 $this->cliArgs = $result->getMediaWikiCliArgs();
387 }
388 $this->overrideMwServices();
389
390 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
391 throw new Exception(
392 get_class( $this ) . ' apparently needsDB but is not in the Database group'
393 );
394 }
395
396 $needsResetDB = false;
397 if ( !self::$dbSetup || $this->needsDB() ) {
398 // set up a DB connection for this test to use
399
400 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
401 self::$reuseDB = $this->getCliArg( 'reuse-db' );
402
403 $this->db = wfGetDB( DB_MASTER );
404
405 $this->checkDbIsSupported();
406
407 if ( !self::$dbSetup ) {
408 $this->setupAllTestDBs();
409 $this->addCoreDBData();
410 }
411
412 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
413 // is available in subclass's setUpBeforeClass() and setUp() methods.
414 // This would also remove the need for the HACK that is oncePerClass().
415 if ( $this->oncePerClass() ) {
416 $this->setUpSchema( $this->db );
417 $this->resetDB( $this->db, $this->tablesUsed );
418 $this->addDBDataOnce();
419 }
420
421 $this->addDBData();
422 $needsResetDB = true;
423 }
424
425 parent::run( $result );
426
427 // We don't mind if we override already-overridden services during cleanup
428 $this->overriddenServices = [];
429
430 if ( $needsResetDB ) {
431 $this->resetDB( $this->db, $this->tablesUsed );
432 }
433
434 self::restoreMwServices();
435 $this->localServices = null;
436 }
437
438 /**
439 * @return bool
440 */
441 private function oncePerClass() {
442 // Remember current test class in the database connection,
443 // so we know when we need to run addData.
444
445 $class = static::class;
446
447 $first = !isset( $this->db->_hasDataForTestClass )
448 || $this->db->_hasDataForTestClass !== $class;
449
450 $this->db->_hasDataForTestClass = $class;
451 return $first;
452 }
453
454 /**
455 * @since 1.21
456 *
457 * @return bool
458 */
459 public function usesTemporaryTables() {
460 return self::$useTemporaryTables;
461 }
462
463 /**
464 * Obtains a new temporary file name
465 *
466 * The obtained filename is enlisted to be removed upon tearDown
467 *
468 * @since 1.20
469 *
470 * @return string Absolute name of the temporary file
471 */
472 protected function getNewTempFile() {
473 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
474 $this->tmpFiles[] = $fileName;
475
476 return $fileName;
477 }
478
479 /**
480 * obtains a new temporary directory
481 *
482 * The obtained directory is enlisted to be removed (recursively with all its contained
483 * files) upon tearDown.
484 *
485 * @since 1.20
486 *
487 * @return string Absolute name of the temporary directory
488 */
489 protected function getNewTempDirectory() {
490 // Starting of with a temporary /file/.
491 $fileName = $this->getNewTempFile();
492
493 // Converting the temporary /file/ to a /directory/
494 // The following is not atomic, but at least we now have a single place,
495 // where temporary directory creation is bundled and can be improved
496 unlink( $fileName );
497 $this->assertTrue( wfMkdirParents( $fileName ) );
498
499 return $fileName;
500 }
501
502 protected function setUp() {
503 parent::setUp();
504 $this->called['setUp'] = true;
505
506 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
507
508 $this->overriddenServices = [];
509
510 // Cleaning up temporary files
511 foreach ( $this->tmpFiles as $fileName ) {
512 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
513 unlink( $fileName );
514 } elseif ( is_dir( $fileName ) ) {
515 wfRecursiveRemoveDir( $fileName );
516 }
517 }
518
519 if ( $this->needsDB() && $this->db ) {
520 // Clean up open transactions
521 while ( $this->db->trxLevel() > 0 ) {
522 $this->db->rollback( __METHOD__, 'flush' );
523 }
524 // Check for unsafe queries
525 if ( $this->db->getType() === 'mysql' ) {
526 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__ );
527 }
528 }
529
530 // Reset all caches between tests.
531 self::resetNonServiceCaches();
532
533 // XXX: reset maintenance triggers
534 // Hook into period lag checks which often happen in long-running scripts
535 $lbFactory = $this->localServices->getDBLoadBalancerFactory();
536 Maintenance::setLBFactoryTriggers( $lbFactory, $this->localServices->getMainConfig() );
537
538 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
539 }
540
541 protected function addTmpFiles( $files ) {
542 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
543 }
544
545 protected function tearDown() {
546 global $wgRequest, $wgSQLMode;
547
548 $status = ob_get_status();
549 if ( isset( $status['name'] ) &&
550 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
551 ) {
552 ob_end_flush();
553 }
554
555 $this->called['tearDown'] = true;
556 // Cleaning up temporary files
557 foreach ( $this->tmpFiles as $fileName ) {
558 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
559 unlink( $fileName );
560 } elseif ( is_dir( $fileName ) ) {
561 wfRecursiveRemoveDir( $fileName );
562 }
563 }
564
565 if ( $this->needsDB() && $this->db ) {
566 // Clean up open transactions
567 while ( $this->db->trxLevel() > 0 ) {
568 $this->db->rollback( __METHOD__, 'flush' );
569 }
570 if ( $this->db->getType() === 'mysql' ) {
571 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ),
572 __METHOD__ );
573 }
574 }
575
576 // Re-enable any disabled deprecation warnings
577 MWDebug::clearLog();
578 // Restore mw globals
579 foreach ( $this->mwGlobals as $key => $value ) {
580 $GLOBALS[$key] = $value;
581 }
582 foreach ( $this->mwGlobalsToUnset as $value ) {
583 unset( $GLOBALS[$value] );
584 }
585 foreach ( $this->iniSettings as $name => $value ) {
586 ini_set( $name, $value );
587 }
588 if (
589 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals ) ||
590 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset )
591 ) {
592 $this->resetNamespaces();
593 }
594 $this->mwGlobals = [];
595 $this->mwGlobalsToUnset = [];
596 $this->restoreLoggers();
597
598 // TODO: move global state into MediaWikiServices
599 RequestContext::resetMain();
600 if ( session_id() !== '' ) {
601 session_write_close();
602 session_id( '' );
603 }
604 $wgRequest = new FauxRequest();
605 MediaWiki\Session\SessionManager::resetCache();
606 MediaWiki\Auth\AuthManager::resetCache();
607
608 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
609
610 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
611 ini_set( 'error_reporting', $this->phpErrorLevel );
612
613 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
614 $newHex = strtoupper( dechex( $phpErrorLevel ) );
615 $message = "PHP error_reporting setting was left dirty: "
616 . "was 0x$oldHex before test, 0x$newHex after test!";
617
618 $this->fail( $message );
619 }
620
621 parent::tearDown();
622 }
623
624 /**
625 * Make sure MediaWikiTestCase extending classes have called their
626 * parent setUp method
627 *
628 * With strict coverage activated in PHP_CodeCoverage, this test would be
629 * marked as risky without the following annotation (T152923).
630 * @coversNothing
631 */
632 final public function testMediaWikiTestCaseParentSetupCalled() {
633 $this->assertArrayHasKey( 'setUp', $this->called,
634 static::class . '::setUp() must call parent::setUp()'
635 );
636 }
637
638 /**
639 * Sets a service, maintaining a stashed version of the previous service to be
640 * restored in tearDown
641 *
642 * @since 1.27
643 *
644 * @param string $name
645 * @param object $object
646 */
647 protected function setService( $name, $object ) {
648 if ( !$this->localServices ) {
649 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
650 }
651
652 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
653 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
654 . 'instance has been replaced by test code.' );
655 }
656
657 $this->overriddenServices[] = $name;
658
659 $this->localServices->disableService( $name );
660 $this->localServices->redefineService(
661 $name,
662 function () use ( $object ) {
663 return $object;
664 }
665 );
666
667 if ( $name === 'ContentLanguage' ) {
668 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
669 }
670 }
671
672 /**
673 * Sets a global, maintaining a stashed version of the previous global to be
674 * restored in tearDown
675 *
676 * The key is added to the array of globals that will be reset afterwards
677 * in the tearDown().
678 *
679 * @par Example
680 * @code
681 * protected function setUp() {
682 * $this->setMwGlobals( 'wgRestrictStuff', true );
683 * }
684 *
685 * function testFoo() {}
686 *
687 * function testBar() {}
688 * $this->assertTrue( self::getX()->doStuff() );
689 *
690 * $this->setMwGlobals( 'wgRestrictStuff', false );
691 * $this->assertTrue( self::getX()->doStuff() );
692 * }
693 *
694 * function testQuux() {}
695 * @endcode
696 *
697 * @param array|string $pairs Key to the global variable, or an array
698 * of key/value pairs.
699 * @param mixed|null $value Value to set the global to (ignored
700 * if an array is given as first argument).
701 *
702 * @note To allow changes to global variables to take effect on global service instances,
703 * call overrideMwServices().
704 *
705 * @since 1.21
706 */
707 protected function setMwGlobals( $pairs, $value = null ) {
708 if ( is_string( $pairs ) ) {
709 $pairs = [ $pairs => $value ];
710 }
711
712 if ( isset( $pairs['wgContLang'] ) ) {
713 throw new MWException(
714 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
715 );
716 }
717
718 $this->doSetMwGlobals( $pairs, $value );
719 }
720
721 /**
722 * An internal method that allows setService() to set globals that tests are not supposed to
723 * touch.
724 */
725 private function doSetMwGlobals( $pairs, $value = null ) {
726 $this->doStashMwGlobals( array_keys( $pairs ) );
727
728 foreach ( $pairs as $key => $value ) {
729 $GLOBALS[$key] = $value;
730 }
731
732 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
733 $this->resetNamespaces();
734 }
735 }
736
737 /**
738 * Set an ini setting for the duration of the test
739 * @param string $name Name of the setting
740 * @param string $value Value to set
741 * @since 1.32
742 */
743 protected function setIniSetting( $name, $value ) {
744 $original = ini_get( $name );
745 $this->iniSettings[$name] = $original;
746 ini_set( $name, $value );
747 }
748
749 /**
750 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
751 * Otherwise old namespace data will lurk and cause bugs.
752 */
753 private function resetNamespaces() {
754 if ( !$this->localServices ) {
755 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
756 }
757
758 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
759 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
760 . 'instance has been replaced by test code.' );
761 }
762
763 MWNamespace::clearCaches();
764 Language::clearCaches();
765
766 // We can't have the TitleFormatter holding on to an old Language object either
767 // @todo We shouldn't need to reset all the aliases here.
768 $this->localServices->resetServiceForTesting( 'TitleFormatter' );
769 $this->localServices->resetServiceForTesting( 'TitleParser' );
770 $this->localServices->resetServiceForTesting( '_MediaWikiTitleCodec' );
771 }
772
773 /**
774 * Check if we can back up a value by performing a shallow copy.
775 * Values which fail this test are copied recursively.
776 *
777 * @param mixed $value
778 * @return bool True if a shallow copy will do; false if a deep copy
779 * is required.
780 */
781 private static function canShallowCopy( $value ) {
782 if ( is_scalar( $value ) || $value === null ) {
783 return true;
784 }
785 if ( is_array( $value ) ) {
786 foreach ( $value as $subValue ) {
787 if ( !is_scalar( $subValue ) && $subValue !== null ) {
788 return false;
789 }
790 }
791 return true;
792 }
793 return false;
794 }
795
796 /**
797 * Stashes the global, will be restored in tearDown()
798 *
799 * Individual test functions may override globals through the setMwGlobals() function
800 * or directly. When directly overriding globals their keys should first be passed to this
801 * method in setUp to avoid breaking global state for other tests
802 *
803 * That way all other tests are executed with the same settings (instead of using the
804 * unreliable local settings for most tests and fix it only for some tests).
805 *
806 * @param array|string $globalKeys Key to the global variable, or an array of keys.
807 *
808 * @note To allow changes to global variables to take effect on global service instances,
809 * call overrideMwServices().
810 *
811 * @since 1.23
812 * @deprecated since 1.32, use setMwGlobals() and don't alter globals directly
813 */
814 protected function stashMwGlobals( $globalKeys ) {
815 wfDeprecated( __METHOD__, '1.32' );
816 $this->doStashMwGlobals( $globalKeys );
817 }
818
819 private function doStashMwGlobals( $globalKeys ) {
820 if ( is_string( $globalKeys ) ) {
821 $globalKeys = [ $globalKeys ];
822 }
823
824 foreach ( $globalKeys as $globalKey ) {
825 // NOTE: make sure we only save the global once or a second call to
826 // setMwGlobals() on the same global would override the original
827 // value.
828 if (
829 !array_key_exists( $globalKey, $this->mwGlobals ) &&
830 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
831 ) {
832 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
833 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
834 continue;
835 }
836 // NOTE: we serialize then unserialize the value in case it is an object
837 // this stops any objects being passed by reference. We could use clone
838 // and if is_object but this does account for objects within objects!
839 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
840 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
841 } elseif (
842 // Many MediaWiki types are safe to clone. These are the
843 // ones that are most commonly stashed.
844 $GLOBALS[$globalKey] instanceof Language ||
845 $GLOBALS[$globalKey] instanceof User ||
846 $GLOBALS[$globalKey] instanceof FauxRequest
847 ) {
848 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
849 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
850 // Serializing Closure only gives a warning on HHVM while
851 // it throws an Exception on Zend.
852 // Workaround for https://github.com/facebook/hhvm/issues/6206
853 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
854 } else {
855 try {
856 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
857 } catch ( Exception $e ) {
858 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
859 }
860 }
861 }
862 }
863 }
864
865 /**
866 * @param mixed $var
867 * @param int $maxDepth
868 *
869 * @return bool
870 */
871 private function containsClosure( $var, $maxDepth = 15 ) {
872 if ( $var instanceof Closure ) {
873 return true;
874 }
875 if ( !is_array( $var ) || $maxDepth === 0 ) {
876 return false;
877 }
878
879 foreach ( $var as $value ) {
880 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
881 return true;
882 }
883 }
884 return false;
885 }
886
887 /**
888 * Merges the given values into a MW global array variable.
889 * Useful for setting some entries in a configuration array, instead of
890 * setting the entire array.
891 *
892 * @param string $name The name of the global, as in wgFooBar
893 * @param array $values The array containing the entries to set in that global
894 *
895 * @throws MWException If the designated global is not an array.
896 *
897 * @note To allow changes to global variables to take effect on global service instances,
898 * call overrideMwServices().
899 *
900 * @since 1.21
901 */
902 protected function mergeMwGlobalArrayValue( $name, $values ) {
903 if ( !isset( $GLOBALS[$name] ) ) {
904 $merged = $values;
905 } else {
906 if ( !is_array( $GLOBALS[$name] ) ) {
907 throw new MWException( "MW global $name is not an array." );
908 }
909
910 // NOTE: do not use array_merge, it screws up for numeric keys.
911 $merged = $GLOBALS[$name];
912 foreach ( $values as $k => $v ) {
913 $merged[$k] = $v;
914 }
915 }
916
917 $this->setMwGlobals( $name, $merged );
918 }
919
920 /**
921 * Stashes the global instance of MediaWikiServices, and installs a new one,
922 * allowing test cases to override settings and services.
923 * The previous instance of MediaWikiServices will be restored on tearDown.
924 *
925 * @since 1.27
926 *
927 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
928 * instance.
929 * @param callable[] $services An associative array of services to re-define. Keys are service
930 * names, values are callables.
931 *
932 * @return MediaWikiServices
933 * @throws MWException
934 */
935 protected function overrideMwServices(
936 Config $configOverrides = null, array $services = []
937 ) {
938 if ( $this->overriddenServices ) {
939 throw new MWException(
940 'The following services were set and are now being unset by overrideMwServices: ' .
941 implode( ', ', $this->overriddenServices )
942 );
943 }
944 $newInstance = self::installMockMwServices( $configOverrides );
945
946 if ( $this->localServices ) {
947 $this->localServices->destroy();
948 }
949
950 $this->localServices = $newInstance;
951
952 foreach ( $services as $name => $callback ) {
953 $newInstance->redefineService( $name, $callback );
954 }
955
956 return $newInstance;
957 }
958
959 /**
960 * Creates a new "mock" MediaWikiServices instance, and installs it.
961 * This effectively resets all cached states in services, with the exception of
962 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
963 * the original MediaWikiServices.
964 *
965 * @note The new original MediaWikiServices instance can later be restored by calling
966 * restoreMwServices(). That original is determined by the first call to this method, or
967 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
968 * and, when appropriate, destroying any other MediaWikiServices instances that may get
969 * replaced when calling this method.
970 *
971 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
972 * instance.
973 *
974 * @return MediaWikiServices the new mock service locator.
975 */
976 public static function installMockMwServices( Config $configOverrides = null ) {
977 // Make sure we have the original service locator
978 if ( !self::$originalServices ) {
979 self::$originalServices = MediaWikiServices::getInstance();
980 }
981
982 if ( !$configOverrides ) {
983 $configOverrides = new HashConfig();
984 }
985
986 $oldConfigFactory = self::$originalServices->getConfigFactory();
987 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
988
989 $testConfig = self::makeTestConfig( null, $configOverrides );
990 $newServices = new MediaWikiServices( $testConfig );
991
992 // Load the default wiring from the specified files.
993 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
994 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
995 $newServices->loadWiringFiles( $wiringFiles );
996
997 // Provide a traditional hook point to allow extensions to configure services.
998 Hooks::run( 'MediaWikiServices', [ $newServices ] );
999
1000 // Use bootstrap config for all configuration.
1001 // This allows config overrides via global variables to take effect.
1002 $bootstrapConfig = $newServices->getBootstrapConfig();
1003 $newServices->resetServiceForTesting( 'ConfigFactory' );
1004 $newServices->redefineService(
1005 'ConfigFactory',
1006 self::makeTestConfigFactoryInstantiator(
1007 $oldConfigFactory,
1008 [ 'main' => $bootstrapConfig ]
1009 )
1010 );
1011 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1012 $newServices->redefineService(
1013 'DBLoadBalancerFactory',
1014 function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
1015 return $oldLoadBalancerFactory;
1016 }
1017 );
1018
1019 MediaWikiServices::forceGlobalInstance( $newServices );
1020 return $newServices;
1021 }
1022
1023 /**
1024 * Restores the original, non-mock MediaWikiServices instance.
1025 * The previously active MediaWikiServices instance is destroyed,
1026 * if it is different from the original that is to be restored.
1027 *
1028 * @note this if for internal use by test framework code. It should never be
1029 * called from inside a test case, a data provider, or a setUp or tearDown method.
1030 *
1031 * @return bool true if the original service locator was restored,
1032 * false if there was nothing too do.
1033 */
1034 public static function restoreMwServices() {
1035 if ( !self::$originalServices ) {
1036 return false;
1037 }
1038
1039 $currentServices = MediaWikiServices::getInstance();
1040
1041 if ( self::$originalServices === $currentServices ) {
1042 return false;
1043 }
1044
1045 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1046 $currentServices->destroy();
1047
1048 return true;
1049 }
1050
1051 /**
1052 * @since 1.27
1053 * @param string|Language $lang
1054 */
1055 public function setUserLang( $lang ) {
1056 RequestContext::getMain()->setLanguage( $lang );
1057 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
1058 }
1059
1060 /**
1061 * @since 1.27
1062 * @param string|Language $lang
1063 */
1064 public function setContentLang( $lang ) {
1065 if ( $lang instanceof Language ) {
1066 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1067 // Set to the exact object requested
1068 $this->setService( 'ContentLanguage', $lang );
1069 } else {
1070 $this->setMwGlobals( 'wgLanguageCode', $lang );
1071 // Let the service handler make up the object. Avoid calling setService(), because if
1072 // we do, overrideMwServices() will complain if it's called later on.
1073 $services = MediaWikiServices::getInstance();
1074 $services->resetServiceForTesting( 'ContentLanguage' );
1075 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1076 }
1077 }
1078
1079 /**
1080 * Alters $wgGroupPermissions for the duration of the test. Can be called
1081 * with an array, like
1082 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1083 * or three values to set a single permission, like
1084 * $this->setGroupPermissions( '*', 'read', false );
1085 *
1086 * @since 1.31
1087 * @param array|string $newPerms Either an array of permissions to change,
1088 * in which case the next two parameters are ignored; or a single string
1089 * identifying a group, to use with the next two parameters.
1090 * @param string|null $newKey
1091 * @param mixed|null $newValue
1092 */
1093 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1094 global $wgGroupPermissions;
1095
1096 if ( is_string( $newPerms ) ) {
1097 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1098 }
1099
1100 $newPermissions = $wgGroupPermissions;
1101 foreach ( $newPerms as $group => $permissions ) {
1102 foreach ( $permissions as $key => $value ) {
1103 $newPermissions[$group][$key] = $value;
1104 }
1105 }
1106
1107 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1108 }
1109
1110 /**
1111 * Sets the logger for a specified channel, for the duration of the test.
1112 * @since 1.27
1113 * @param string $channel
1114 * @param LoggerInterface $logger
1115 */
1116 protected function setLogger( $channel, LoggerInterface $logger ) {
1117 // TODO: Once loggers are managed by MediaWikiServices, use
1118 // overrideMwServices() to set loggers.
1119
1120 $provider = LoggerFactory::getProvider();
1121 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1122 $singletons = $wrappedProvider->singletons;
1123 if ( $provider instanceof MonologSpi ) {
1124 if ( !isset( $this->loggers[$channel] ) ) {
1125 $this->loggers[$channel] = $singletons['loggers'][$channel] ?? null;
1126 }
1127 $singletons['loggers'][$channel] = $logger;
1128 } elseif ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1129 if ( !isset( $this->loggers[$channel] ) ) {
1130 $this->loggers[$channel] = $singletons[$channel] ?? null;
1131 }
1132 $singletons[$channel] = $logger;
1133 } else {
1134 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
1135 . ' is not implemented' );
1136 }
1137 $wrappedProvider->singletons = $singletons;
1138 }
1139
1140 /**
1141 * Restores loggers replaced by setLogger().
1142 * @since 1.27
1143 */
1144 private function restoreLoggers() {
1145 $provider = LoggerFactory::getProvider();
1146 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1147 $singletons = $wrappedProvider->singletons;
1148 foreach ( $this->loggers as $channel => $logger ) {
1149 if ( $provider instanceof MonologSpi ) {
1150 if ( $logger === null ) {
1151 unset( $singletons['loggers'][$channel] );
1152 } else {
1153 $singletons['loggers'][$channel] = $logger;
1154 }
1155 } elseif ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1156 if ( $logger === null ) {
1157 unset( $singletons[$channel] );
1158 } else {
1159 $singletons[$channel] = $logger;
1160 }
1161 }
1162 }
1163 $wrappedProvider->singletons = $singletons;
1164 $this->loggers = [];
1165 }
1166
1167 /**
1168 * @return string
1169 * @since 1.18
1170 */
1171 public function dbPrefix() {
1172 return self::getTestPrefixFor( $this->db );
1173 }
1174
1175 /**
1176 * @param IDatabase $db
1177 * @return string
1178 * @since 1.32
1179 */
1180 public static function getTestPrefixFor( IDatabase $db ) {
1181 return $db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
1182 }
1183
1184 /**
1185 * @return bool
1186 * @since 1.18
1187 */
1188 public function needsDB() {
1189 // If the test says it uses database tables, it needs the database
1190 return $this->tablesUsed || $this->isTestInDatabaseGroup();
1191 }
1192
1193 /**
1194 * @return bool
1195 * @since 1.32
1196 */
1197 protected function isTestInDatabaseGroup() {
1198 // If the test class says it belongs to the Database group, it needs the database.
1199 // NOTE: This ONLY checks for the group in the class level doc comment.
1200 $rc = new ReflectionClass( $this );
1201 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1202 }
1203
1204 /**
1205 * Insert a new page.
1206 *
1207 * Should be called from addDBData().
1208 *
1209 * @since 1.25 ($namespace in 1.28)
1210 * @param string|Title $pageName Page name or title
1211 * @param string $text Page's content
1212 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1213 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1214 * @return array Title object and page id
1215 * @throws MWException If this test cases's needsDB() method doesn't return true.
1216 * Test cases can use "@group Database" to enable database test support,
1217 * or list the tables under testing in $this->tablesUsed, or override the
1218 * needsDB() method.
1219 */
1220 protected function insertPage(
1221 $pageName,
1222 $text = 'Sample page for unit test.',
1223 $namespace = null,
1224 User $user = null
1225 ) {
1226 if ( !$this->needsDB() ) {
1227 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1228 ' method should return true. Use @group Database or $this->tablesUsed.' );
1229 }
1230
1231 if ( is_string( $pageName ) ) {
1232 $title = Title::newFromText( $pageName, $namespace );
1233 } else {
1234 $title = $pageName;
1235 }
1236
1237 if ( !$user ) {
1238 $user = static::getTestSysop()->getUser();
1239 }
1240 $comment = __METHOD__ . ': Sample page for unit test.';
1241
1242 $page = WikiPage::factory( $title );
1243 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
1244
1245 return [
1246 'title' => $title,
1247 'id' => $page->getId(),
1248 ];
1249 }
1250
1251 /**
1252 * Stub. If a test suite needs to add additional data to the database, it should
1253 * implement this method and do so. This method is called once per test suite
1254 * (i.e. once per class).
1255 *
1256 * Note data added by this method may be removed by resetDB() depending on
1257 * the contents of $tablesUsed.
1258 *
1259 * To add additional data between test function runs, override prepareDB().
1260 *
1261 * @see addDBData()
1262 * @see resetDB()
1263 *
1264 * @since 1.27
1265 */
1266 public function addDBDataOnce() {
1267 }
1268
1269 /**
1270 * Stub. Subclasses may override this to prepare the database.
1271 * Called before every test run (test function or data set).
1272 *
1273 * @see addDBDataOnce()
1274 * @see resetDB()
1275 *
1276 * @since 1.18
1277 */
1278 public function addDBData() {
1279 }
1280
1281 /**
1282 * @since 1.32
1283 */
1284 protected function addCoreDBData() {
1285 if ( $this->db->getType() == 'oracle' ) {
1286 # Insert 0 user to prevent FK violations
1287 # Anonymous user
1288 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1289 $this->db->insert( 'user', [
1290 'user_id' => 0,
1291 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
1292 }
1293
1294 # Insert 0 page to prevent FK violations
1295 # Blank page
1296 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1297 $this->db->insert( 'page', [
1298 'page_id' => 0,
1299 'page_namespace' => 0,
1300 'page_title' => ' ',
1301 'page_restrictions' => null,
1302 'page_is_redirect' => 0,
1303 'page_is_new' => 0,
1304 'page_random' => 0,
1305 'page_touched' => $this->db->timestamp(),
1306 'page_latest' => 0,
1307 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1308 }
1309 }
1310
1311 SiteStatsInit::doPlaceholderInit();
1312
1313 User::resetIdByNameCache();
1314
1315 // Make sysop user
1316 $user = static::getTestSysop()->getUser();
1317
1318 // Make 1 page with 1 revision
1319 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1320 if ( $page->getId() == 0 ) {
1321 $page->doEditContent(
1322 new WikitextContent( 'UTContent' ),
1323 'UTPageSummary',
1324 EDIT_NEW | EDIT_SUPPRESS_RC,
1325 false,
1326 $user
1327 );
1328 // an edit always attempt to purge backlink links such as history
1329 // pages. That is unnecessary.
1330 JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->delete();
1331 // WikiPages::doEditUpdates randomly adds RC purges
1332 JobQueueGroup::singleton()->get( 'recentChangesUpdate' )->delete();
1333
1334 // doEditContent() probably started the session via
1335 // User::loadFromSession(). Close it now.
1336 if ( session_id() !== '' ) {
1337 session_write_close();
1338 session_id( '' );
1339 }
1340 }
1341 }
1342
1343 /**
1344 * Restores MediaWiki to using the table set (table prefix) it was using before
1345 * setupTestDB() was called. Useful if we need to perform database operations
1346 * after the test run has finished (such as saving logs or profiling info).
1347 *
1348 * This is called by phpunit/bootstrap.php after the last test.
1349 *
1350 * @since 1.21
1351 */
1352 public static function teardownTestDB() {
1353 global $wgJobClasses;
1354
1355 if ( !self::$dbSetup ) {
1356 return;
1357 }
1358
1359 Hooks::run( 'UnitTestsBeforeDatabaseTeardown' );
1360
1361 foreach ( $wgJobClasses as $type => $class ) {
1362 // Delete any jobs under the clone DB (or old prefix in other stores)
1363 JobQueueGroup::singleton()->get( $type )->delete();
1364 }
1365
1366 CloneDatabase::changePrefix( self::$oldTablePrefix );
1367
1368 self::$oldTablePrefix = false;
1369 self::$dbSetup = false;
1370 }
1371
1372 /**
1373 * Setups a database with cloned tables using the given prefix.
1374 *
1375 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1376 * Otherwise, it will clone the tables and change the prefix.
1377 *
1378 * @param IMaintainableDatabase $db Database to use
1379 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1380 * automatically for $db.
1381 * @return bool True if tables were cloned, false if only the prefix was changed
1382 */
1383 protected static function setupDatabaseWithTestPrefix(
1384 IMaintainableDatabase $db,
1385 $prefix = null
1386 ) {
1387 if ( $prefix === null ) {
1388 $prefix = self::getTestPrefixFor( $db );
1389 }
1390
1391 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1392 $db->tablePrefix( $prefix );
1393 return false;
1394 }
1395
1396 if ( !isset( $db->_originalTablePrefix ) ) {
1397 $oldPrefix = $db->tablePrefix();
1398
1399 if ( $oldPrefix === $prefix ) {
1400 // table already has the correct prefix, but presumably no cloned tables
1401 $oldPrefix = self::$oldTablePrefix;
1402 }
1403
1404 $db->tablePrefix( $oldPrefix );
1405 $tablesCloned = self::listTables( $db );
1406 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1407 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1408
1409 $dbClone->cloneTableStructure();
1410
1411 $db->tablePrefix( $prefix );
1412 $db->_originalTablePrefix = $oldPrefix;
1413 }
1414
1415 return true;
1416 }
1417
1418 /**
1419 * Set up all test DBs
1420 */
1421 public function setupAllTestDBs() {
1422 global $wgDBprefix;
1423
1424 self::$oldTablePrefix = $wgDBprefix;
1425
1426 $testPrefix = $this->dbPrefix();
1427
1428 // switch to a temporary clone of the database
1429 self::setupTestDB( $this->db, $testPrefix );
1430
1431 if ( self::isUsingExternalStoreDB() ) {
1432 self::setupExternalStoreTestDBs( $testPrefix );
1433 }
1434
1435 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1436 // *any* database connections to operate on live data.
1437 CloneDatabase::changePrefix( $testPrefix );
1438 }
1439
1440 /**
1441 * Creates an empty skeleton of the wiki database by cloning its structure
1442 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1443 * use the new set of tables (aka schema) instead of the original set.
1444 *
1445 * This is used to generate a dummy table set, typically consisting of temporary
1446 * tables, that will be used by tests instead of the original wiki database tables.
1447 *
1448 * @since 1.21
1449 *
1450 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1451 * by teardownTestDB() to return the wiki to using the original table set.
1452 *
1453 * @note this method only works when first called. Subsequent calls have no effect,
1454 * even if using different parameters.
1455 *
1456 * @param Database $db The database connection
1457 * @param string $prefix The prefix to use for the new table set (aka schema).
1458 *
1459 * @throws MWException If the database table prefix is already $prefix
1460 */
1461 public static function setupTestDB( Database $db, $prefix ) {
1462 if ( self::$dbSetup ) {
1463 return;
1464 }
1465
1466 if ( $db->tablePrefix() === $prefix ) {
1467 throw new MWException(
1468 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1469 }
1470
1471 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1472 // and Database no longer use global state.
1473
1474 self::$dbSetup = true;
1475
1476 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1477 return;
1478 }
1479
1480 // Assuming this isn't needed for External Store database, and not sure if the procedure
1481 // would be available there.
1482 if ( $db->getType() == 'oracle' ) {
1483 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__ );
1484 }
1485
1486 Hooks::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1487 }
1488
1489 /**
1490 * Clones the External Store database(s) for testing
1491 *
1492 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1493 * if not given.
1494 */
1495 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1496 $connections = self::getExternalStoreDatabaseConnections();
1497 foreach ( $connections as $dbw ) {
1498 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1499 }
1500 }
1501
1502 /**
1503 * Gets master database connections for all of the ExternalStoreDB
1504 * stores configured in $wgDefaultExternalStore.
1505 *
1506 * @return Database[] Array of Database master connections
1507 */
1508 protected static function getExternalStoreDatabaseConnections() {
1509 global $wgDefaultExternalStore;
1510
1511 /** @var ExternalStoreDB $externalStoreDB */
1512 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1513 $defaultArray = (array)$wgDefaultExternalStore;
1514 $dbws = [];
1515 foreach ( $defaultArray as $url ) {
1516 if ( strpos( $url, 'DB://' ) === 0 ) {
1517 list( $proto, $cluster ) = explode( '://', $url, 2 );
1518 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1519 // requires Database instead of plain DBConnRef/IDatabase
1520 $dbws[] = $externalStoreDB->getMaster( $cluster );
1521 }
1522 }
1523
1524 return $dbws;
1525 }
1526
1527 /**
1528 * Check whether ExternalStoreDB is being used
1529 *
1530 * @return bool True if it's being used
1531 */
1532 protected static function isUsingExternalStoreDB() {
1533 global $wgDefaultExternalStore;
1534 if ( !$wgDefaultExternalStore ) {
1535 return false;
1536 }
1537
1538 $defaultArray = (array)$wgDefaultExternalStore;
1539 foreach ( $defaultArray as $url ) {
1540 if ( strpos( $url, 'DB://' ) === 0 ) {
1541 return true;
1542 }
1543 }
1544
1545 return false;
1546 }
1547
1548 /**
1549 * @throws LogicException if the given database connection is not a set up to use
1550 * mock tables.
1551 *
1552 * @since 1.31 this is no longer private.
1553 */
1554 protected function ensureMockDatabaseConnection( IDatabase $db ) {
1555 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1556 throw new LogicException(
1557 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1558 );
1559 }
1560 }
1561
1562 private static $schemaOverrideDefaults = [
1563 'scripts' => [],
1564 'create' => [],
1565 'drop' => [],
1566 'alter' => [],
1567 ];
1568
1569 /**
1570 * Stub. If a test suite needs to test against a specific database schema, it should
1571 * override this method and return the appropriate information from it.
1572 *
1573 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1574 * May be used to check the current state of the schema, to determine what
1575 * overrides are needed.
1576 *
1577 * @return array An associative array with the following fields:
1578 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1579 * - 'create': A list of tables created (may or may not exist in the original schema).
1580 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1581 * - 'alter': A list of tables altered (expected to be present in the original schema).
1582 */
1583 protected function getSchemaOverrides( IMaintainableDatabase $db ) {
1584 return [];
1585 }
1586
1587 /**
1588 * Undoes the specified schema overrides..
1589 * Called once per test class, just before addDataOnce().
1590 *
1591 * @param IMaintainableDatabase $db
1592 * @param array $oldOverrides
1593 */
1594 private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOverrides ) {
1595 $this->ensureMockDatabaseConnection( $db );
1596
1597 $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
1598 $originalTables = $this->listOriginalTables( $db );
1599
1600 // Drop tables that need to be restored or removed.
1601 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1602
1603 // Restore tables that have been dropped or created or altered,
1604 // if they exist in the original schema.
1605 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1606 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1607
1608 if ( $tablesToDrop ) {
1609 $this->dropMockTables( $db, $tablesToDrop );
1610 }
1611
1612 if ( $tablesToRestore ) {
1613 $this->recloneMockTables( $db, $tablesToRestore );
1614 }
1615 }
1616
1617 /**
1618 * Applies the schema overrides returned by getSchemaOverrides(),
1619 * after undoing any previously applied schema overrides.
1620 * Called once per test class, just before addDataOnce().
1621 */
1622 private function setUpSchema( IMaintainableDatabase $db ) {
1623 // Undo any active overrides.
1624 $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDefaults;
1625
1626 if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) {
1627 $this->undoSchemaOverrides( $db, $oldOverrides );
1628 }
1629
1630 // Determine new overrides.
1631 $overrides = $this->getSchemaOverrides( $db ) + self::$schemaOverrideDefaults;
1632
1633 $extraKeys = array_diff(
1634 array_keys( $overrides ),
1635 array_keys( self::$schemaOverrideDefaults )
1636 );
1637
1638 if ( $extraKeys ) {
1639 throw new InvalidArgumentException(
1640 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1641 );
1642 }
1643
1644 if ( !$overrides['scripts'] ) {
1645 // no scripts to run
1646 return;
1647 }
1648
1649 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1650 throw new InvalidArgumentException(
1651 'Schema override scripts given, but no tables are declared to be '
1652 . 'created, dropped or altered.'
1653 );
1654 }
1655
1656 $this->ensureMockDatabaseConnection( $db );
1657
1658 // Drop the tables that will be created by the schema scripts.
1659 $originalTables = $this->listOriginalTables( $db );
1660 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1661
1662 if ( $tablesToDrop ) {
1663 $this->dropMockTables( $db, $tablesToDrop );
1664 }
1665
1666 // Run schema override scripts.
1667 foreach ( $overrides['scripts'] as $script ) {
1668 $db->sourceFile(
1669 $script,
1670 null,
1671 null,
1672 __METHOD__,
1673 function ( $cmd ) {
1674 return $this->mungeSchemaUpdateQuery( $cmd );
1675 }
1676 );
1677 }
1678
1679 $db->_schemaOverrides = $overrides;
1680 }
1681
1682 private function mungeSchemaUpdateQuery( $cmd ) {
1683 return self::$useTemporaryTables
1684 ? preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1685 : $cmd;
1686 }
1687
1688 /**
1689 * Drops the given mock tables.
1690 *
1691 * @param IMaintainableDatabase $db
1692 * @param array $tables
1693 */
1694 private function dropMockTables( IMaintainableDatabase $db, array $tables ) {
1695 $this->ensureMockDatabaseConnection( $db );
1696
1697 foreach ( $tables as $tbl ) {
1698 $tbl = $db->tableName( $tbl );
1699 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
1700 }
1701 }
1702
1703 /**
1704 * Lists all tables in the live database schema, without a prefix.
1705 *
1706 * @param IMaintainableDatabase $db
1707 * @return array
1708 */
1709 private function listOriginalTables( IMaintainableDatabase $db ) {
1710 if ( !isset( $db->_originalTablePrefix ) ) {
1711 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1712 }
1713
1714 $originalTables = $db->listTables( $db->_originalTablePrefix, __METHOD__ );
1715
1716 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1717 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix, '/' ) . '/';
1718
1719 $originalTables = array_filter(
1720 $originalTables,
1721 function ( $pt ) use ( $unittestPrefixRegex ) {
1722 return !preg_match( $unittestPrefixRegex, $pt );
1723 }
1724 );
1725
1726 $originalTables = array_map(
1727 function ( $pt ) use ( $originalPrefixRegex ) {
1728 return preg_replace( $originalPrefixRegex, '', $pt );
1729 },
1730 $originalTables
1731 );
1732
1733 return array_unique( $originalTables );
1734 }
1735
1736 /**
1737 * Re-clones the given mock tables to restore them based on the live database schema.
1738 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1739 * should be called first.
1740 *
1741 * @param IMaintainableDatabase $db
1742 * @param array $tables
1743 */
1744 private function recloneMockTables( IMaintainableDatabase $db, array $tables ) {
1745 $this->ensureMockDatabaseConnection( $db );
1746
1747 if ( !isset( $db->_originalTablePrefix ) ) {
1748 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1749 }
1750
1751 $originalTables = $this->listOriginalTables( $db );
1752 $tables = array_intersect( $tables, $originalTables );
1753
1754 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix );
1755 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1756
1757 $dbClone->cloneTableStructure();
1758 }
1759
1760 /**
1761 * Empty all tables so they can be repopulated for tests
1762 *
1763 * @param Database $db|null Database to reset
1764 * @param array $tablesUsed Tables to reset
1765 */
1766 private function resetDB( $db, $tablesUsed ) {
1767 if ( $db ) {
1768 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1769 $pageTables = [
1770 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1771 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1772 ];
1773 $coreDBDataTables = array_merge( $userTables, $pageTables );
1774
1775 // If any of the user or page tables were marked as used, we should clear all of them.
1776 if ( array_intersect( $tablesUsed, $userTables ) ) {
1777 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1778 TestUserRegistry::clear();
1779 }
1780 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1781 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1782 }
1783
1784 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1785 // instead of user/text. But Postgres does not remap the
1786 // table name in tableExists(), so we mark the real table
1787 // names as being used.
1788 if ( $db->getType() === 'postgres' ) {
1789 if ( in_array( 'user', $tablesUsed ) ) {
1790 $tablesUsed[] = 'mwuser';
1791 }
1792 if ( in_array( 'text', $tablesUsed ) ) {
1793 $tablesUsed[] = 'pagecontent';
1794 }
1795 }
1796
1797 foreach ( $tablesUsed as $tbl ) {
1798 $this->truncateTable( $tbl, $db );
1799 }
1800
1801 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1802 // Reset services that may contain information relating to the truncated tables
1803 $this->overrideMwServices();
1804 // Re-add core DB data that was deleted
1805 $this->addCoreDBData();
1806 }
1807 }
1808 }
1809
1810 /**
1811 * Empties the given table and resets any auto-increment counters.
1812 * Will also purge caches associated with some well known tables.
1813 * If the table is not know, this method just returns.
1814 *
1815 * @param string $tableName
1816 * @param IDatabase|null $db
1817 */
1818 protected function truncateTable( $tableName, IDatabase $db = null ) {
1819 if ( !$db ) {
1820 $db = $this->db;
1821 }
1822
1823 if ( !$db->tableExists( $tableName ) ) {
1824 return;
1825 }
1826
1827 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1828
1829 if ( $truncate ) {
1830 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__ );
1831 } else {
1832 $db->delete( $tableName, '*', __METHOD__ );
1833 }
1834
1835 if ( $db instanceof DatabasePostgres || $db instanceof DatabaseSqlite ) {
1836 // Reset the table's sequence too.
1837 $db->resetSequenceForTable( $tableName, __METHOD__ );
1838 }
1839
1840 // re-initialize site_stats table
1841 if ( $tableName === 'site_stats' ) {
1842 SiteStatsInit::doPlaceholderInit();
1843 }
1844 }
1845
1846 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1847 $tableName = substr( $tableName, strlen( $prefix ) );
1848 }
1849
1850 private static function isNotUnittest( $table ) {
1851 return strpos( $table, self::DB_PREFIX ) !== 0;
1852 }
1853
1854 /**
1855 * @since 1.18
1856 *
1857 * @param IMaintainableDatabase $db
1858 *
1859 * @return array
1860 */
1861 public static function listTables( IMaintainableDatabase $db ) {
1862 $prefix = $db->tablePrefix();
1863 $tables = $db->listTables( $prefix, __METHOD__ );
1864
1865 if ( $db->getType() === 'mysql' ) {
1866 static $viewListCache = null;
1867 if ( $viewListCache === null ) {
1868 $viewListCache = $db->listViews( null, __METHOD__ );
1869 }
1870 // T45571: cannot clone VIEWs under MySQL
1871 $tables = array_diff( $tables, $viewListCache );
1872 }
1873 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1874
1875 // Don't duplicate test tables from the previous fataled run
1876 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1877
1878 if ( $db->getType() == 'sqlite' ) {
1879 $tables = array_flip( $tables );
1880 // these are subtables of searchindex and don't need to be duped/dropped separately
1881 unset( $tables['searchindex_content'] );
1882 unset( $tables['searchindex_segdir'] );
1883 unset( $tables['searchindex_segments'] );
1884 $tables = array_flip( $tables );
1885 }
1886
1887 return $tables;
1888 }
1889
1890 /**
1891 * Copy test data from one database connection to another.
1892 *
1893 * This should only be used for small data sets.
1894 *
1895 * @param IDatabase $source
1896 * @param IDatabase $target
1897 */
1898 public function copyTestData( IDatabase $source, IDatabase $target ) {
1899 if ( $this->db->getType() === 'sqlite' ) {
1900 // SQLite uses a non-temporary copy of the searchindex table for testing,
1901 // which gets deleted and re-created when setting up the secondary connection,
1902 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1903 throw new RuntimeException(
1904 'Setting up a secondary database connection with test data is currently not'
1905 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1906 );
1907 }
1908
1909 $tables = self::listOriginalTables( $source );
1910
1911 foreach ( $tables as $table ) {
1912 $res = $source->select( $table, '*', [], __METHOD__ );
1913 $allRows = [];
1914
1915 foreach ( $res as $row ) {
1916 $allRows[] = (array)$row;
1917 }
1918
1919 $target->insert( $table, $allRows, __METHOD__, [ 'IGNORE' ] );
1920 }
1921 }
1922
1923 /**
1924 * @throws MWException
1925 * @since 1.18
1926 */
1927 protected function checkDbIsSupported() {
1928 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1929 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1930 }
1931 }
1932
1933 /**
1934 * @since 1.18
1935 * @param string $offset
1936 * @return mixed
1937 */
1938 public function getCliArg( $offset ) {
1939 return $this->cliArgs[$offset] ?? null;
1940 }
1941
1942 /**
1943 * @since 1.18
1944 * @param string $offset
1945 * @param mixed $value
1946 */
1947 public function setCliArg( $offset, $value ) {
1948 $this->cliArgs[$offset] = $value;
1949 }
1950
1951 /**
1952 * Don't throw a warning if $function is deprecated and called later
1953 *
1954 * @since 1.19
1955 *
1956 * @param string $function
1957 */
1958 public function hideDeprecated( $function ) {
1959 Wikimedia\suppressWarnings();
1960 wfDeprecated( $function );
1961 Wikimedia\restoreWarnings();
1962 }
1963
1964 /**
1965 * Asserts that the given database query yields the rows given by $expectedRows.
1966 * The expected rows should be given as indexed (not associative) arrays, with
1967 * the values given in the order of the columns in the $fields parameter.
1968 * Note that the rows are sorted by the columns given in $fields.
1969 *
1970 * @since 1.20
1971 *
1972 * @param string|array $table The table(s) to query
1973 * @param string|array $fields The columns to include in the result (and to sort by)
1974 * @param string|array $condition "where" condition(s)
1975 * @param array $expectedRows An array of arrays giving the expected rows.
1976 * @param array $options Options for the query
1977 * @param array $join_conds Join conditions for the query
1978 *
1979 * @throws MWException If this test cases's needsDB() method doesn't return true.
1980 * Test cases can use "@group Database" to enable database test support,
1981 * or list the tables under testing in $this->tablesUsed, or override the
1982 * needsDB() method.
1983 */
1984 protected function assertSelect(
1985 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1986 ) {
1987 if ( !$this->needsDB() ) {
1988 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1989 ' method should return true. Use @group Database or $this->tablesUsed.' );
1990 }
1991
1992 $db = wfGetDB( DB_REPLICA );
1993
1994 $res = $db->select(
1995 $table,
1996 $fields,
1997 $condition,
1998 wfGetCaller(),
1999 $options + [ 'ORDER BY' => $fields ],
2000 $join_conds
2001 );
2002 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2003
2004 $i = 0;
2005
2006 foreach ( $expectedRows as $expected ) {
2007 $r = $res->fetchRow();
2008 self::stripStringKeys( $r );
2009
2010 $i += 1;
2011 $this->assertNotEmpty( $r, "row #$i missing" );
2012
2013 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2014 }
2015
2016 $r = $res->fetchRow();
2017 self::stripStringKeys( $r );
2018
2019 $this->assertFalse( $r, "found extra row (after #$i)" );
2020 }
2021
2022 /**
2023 * Utility method taking an array of elements and wrapping
2024 * each element in its own array. Useful for data providers
2025 * that only return a single argument.
2026 *
2027 * @since 1.20
2028 *
2029 * @param array $elements
2030 *
2031 * @return array
2032 */
2033 protected function arrayWrap( array $elements ) {
2034 return array_map(
2035 function ( $element ) {
2036 return [ $element ];
2037 },
2038 $elements
2039 );
2040 }
2041
2042 /**
2043 * Assert that two arrays are equal. By default this means that both arrays need to hold
2044 * the same set of values. Using additional arguments, order and associated key can also
2045 * be set as relevant.
2046 *
2047 * @since 1.20
2048 *
2049 * @param array $expected
2050 * @param array $actual
2051 * @param bool $ordered If the order of the values should match
2052 * @param bool $named If the keys should match
2053 */
2054 protected function assertArrayEquals( array $expected, array $actual,
2055 $ordered = false, $named = false
2056 ) {
2057 if ( !$ordered ) {
2058 $this->objectAssociativeSort( $expected );
2059 $this->objectAssociativeSort( $actual );
2060 }
2061
2062 if ( !$named ) {
2063 $expected = array_values( $expected );
2064 $actual = array_values( $actual );
2065 }
2066
2067 call_user_func_array(
2068 [ $this, 'assertEquals' ],
2069 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2070 );
2071 }
2072
2073 /**
2074 * Put each HTML element on its own line and then equals() the results
2075 *
2076 * Use for nicely formatting of PHPUnit diff output when comparing very
2077 * simple HTML
2078 *
2079 * @since 1.20
2080 *
2081 * @param string $expected HTML on oneline
2082 * @param string $actual HTML on oneline
2083 * @param string $msg Optional message
2084 */
2085 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2086 $expected = str_replace( '>', ">\n", $expected );
2087 $actual = str_replace( '>', ">\n", $actual );
2088
2089 $this->assertEquals( $expected, $actual, $msg );
2090 }
2091
2092 /**
2093 * Does an associative sort that works for objects.
2094 *
2095 * @since 1.20
2096 *
2097 * @param array &$array
2098 */
2099 protected function objectAssociativeSort( array &$array ) {
2100 uasort(
2101 $array,
2102 function ( $a, $b ) {
2103 return serialize( $a ) <=> serialize( $b );
2104 }
2105 );
2106 }
2107
2108 /**
2109 * Utility function for eliminating all string keys from an array.
2110 * Useful to turn a database result row as returned by fetchRow() into
2111 * a pure indexed array.
2112 *
2113 * @since 1.20
2114 *
2115 * @param mixed &$r The array to remove string keys from.
2116 */
2117 protected static function stripStringKeys( &$r ) {
2118 if ( !is_array( $r ) ) {
2119 return;
2120 }
2121
2122 foreach ( $r as $k => $v ) {
2123 if ( is_string( $k ) ) {
2124 unset( $r[$k] );
2125 }
2126 }
2127 }
2128
2129 /**
2130 * Asserts that the provided variable is of the specified
2131 * internal type or equals the $value argument. This is useful
2132 * for testing return types of functions that return a certain
2133 * type or *value* when not set or on error.
2134 *
2135 * @since 1.20
2136 *
2137 * @param string $type
2138 * @param mixed $actual
2139 * @param mixed $value
2140 * @param string $message
2141 */
2142 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2143 if ( $actual === $value ) {
2144 $this->assertTrue( true, $message );
2145 } else {
2146 $this->assertType( $type, $actual, $message );
2147 }
2148 }
2149
2150 /**
2151 * Asserts the type of the provided value. This can be either
2152 * in internal type such as boolean or integer, or a class or
2153 * interface the value extends or implements.
2154 *
2155 * @since 1.20
2156 *
2157 * @param string $type
2158 * @param mixed $actual
2159 * @param string $message
2160 */
2161 protected function assertType( $type, $actual, $message = '' ) {
2162 if ( class_exists( $type ) || interface_exists( $type ) ) {
2163 $this->assertInstanceOf( $type, $actual, $message );
2164 } else {
2165 $this->assertInternalType( $type, $actual, $message );
2166 }
2167 }
2168
2169 /**
2170 * Returns true if the given namespace defaults to Wikitext
2171 * according to $wgNamespaceContentModels
2172 *
2173 * @param int $ns The namespace ID to check
2174 *
2175 * @return bool
2176 * @since 1.21
2177 */
2178 protected function isWikitextNS( $ns ) {
2179 global $wgNamespaceContentModels;
2180
2181 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2182 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2183 }
2184
2185 return true;
2186 }
2187
2188 /**
2189 * Returns the ID of a namespace that defaults to Wikitext.
2190 *
2191 * @throws MWException If there is none.
2192 * @return int The ID of the wikitext Namespace
2193 * @since 1.21
2194 */
2195 protected function getDefaultWikitextNS() {
2196 global $wgNamespaceContentModels;
2197
2198 static $wikitextNS = null; // this is not going to change
2199 if ( $wikitextNS !== null ) {
2200 return $wikitextNS;
2201 }
2202
2203 // quickly short out on most common case:
2204 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2205 return NS_MAIN;
2206 }
2207
2208 // NOTE: prefer content namespaces
2209 $namespaces = array_unique( array_merge(
2210 MWNamespace::getContentNamespaces(),
2211 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2212 MWNamespace::getValidNamespaces()
2213 ) );
2214
2215 $namespaces = array_diff( $namespaces, [
2216 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2217 ] );
2218
2219 $talk = array_filter( $namespaces, function ( $ns ) {
2220 return MWNamespace::isTalk( $ns );
2221 } );
2222
2223 // prefer non-talk pages
2224 $namespaces = array_diff( $namespaces, $talk );
2225 $namespaces = array_merge( $namespaces, $talk );
2226
2227 // check default content model of each namespace
2228 foreach ( $namespaces as $ns ) {
2229 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2230 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2231 ) {
2232 $wikitextNS = $ns;
2233
2234 return $wikitextNS;
2235 }
2236 }
2237
2238 // give up
2239 // @todo Inside a test, we could skip the test as incomplete.
2240 // But frequently, this is used in fixture setup.
2241 throw new MWException( "No namespace defaults to wikitext!" );
2242 }
2243
2244 /**
2245 * Check, if $wgDiff3 is set and ready to merge
2246 * Will mark the calling test as skipped, if not ready
2247 *
2248 * @since 1.21
2249 */
2250 protected function markTestSkippedIfNoDiff3() {
2251 global $wgDiff3;
2252
2253 # This check may also protect against code injection in
2254 # case of broken installations.
2255 Wikimedia\suppressWarnings();
2256 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2257 Wikimedia\restoreWarnings();
2258
2259 if ( !$haveDiff3 ) {
2260 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2261 }
2262 }
2263
2264 /**
2265 * Check if $extName is a loaded PHP extension, will skip the
2266 * test whenever it is not loaded.
2267 *
2268 * @since 1.21
2269 * @param string $extName
2270 * @return bool
2271 */
2272 protected function checkPHPExtension( $extName ) {
2273 $loaded = extension_loaded( $extName );
2274 if ( !$loaded ) {
2275 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2276 }
2277
2278 return $loaded;
2279 }
2280
2281 /**
2282 * Skip the test if using the specified database type
2283 *
2284 * @param string $type Database type
2285 * @since 1.32
2286 */
2287 protected function markTestSkippedIfDbType( $type ) {
2288 if ( $this->db->getType() === $type ) {
2289 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2290 }
2291 }
2292
2293 /**
2294 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2295 * @param string $buffer
2296 * @return string
2297 */
2298 public static function wfResetOutputBuffersBarrier( $buffer ) {
2299 return $buffer;
2300 }
2301
2302 /**
2303 * Create a temporary hook handler which will be reset by tearDown.
2304 * This replaces other handlers for the same hook.
2305 * @param string $hookName Hook name
2306 * @param mixed $handler Value suitable for a hook handler
2307 * @since 1.28
2308 */
2309 protected function setTemporaryHook( $hookName, $handler ) {
2310 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2311 }
2312
2313 /**
2314 * Check whether file contains given data.
2315 * @param string $fileName
2316 * @param string $actualData
2317 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2318 * and skip the test.
2319 * @param string $msg
2320 * @since 1.30
2321 */
2322 protected function assertFileContains(
2323 $fileName,
2324 $actualData,
2325 $createIfMissing = false,
2326 $msg = ''
2327 ) {
2328 if ( $createIfMissing ) {
2329 if ( !file_exists( $fileName ) ) {
2330 file_put_contents( $fileName, $actualData );
2331 $this->markTestSkipped( 'Data file $fileName does not exist' );
2332 }
2333 } else {
2334 self::assertFileExists( $fileName );
2335 }
2336 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2337 }
2338
2339 /**
2340 * Edits or creates a page/revision
2341 * @param string $pageName Page title
2342 * @param string $text Content of the page
2343 * @param string $summary Optional summary string for the revision
2344 * @param int $defaultNs Optional namespace id
2345 * @return array Array as returned by WikiPage::doEditContent()
2346 * @throws MWException If this test cases's needsDB() method doesn't return true.
2347 * Test cases can use "@group Database" to enable database test support,
2348 * or list the tables under testing in $this->tablesUsed, or override the
2349 * needsDB() method.
2350 */
2351 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
2352 if ( !$this->needsDB() ) {
2353 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2354 ' method should return true. Use @group Database or $this->tablesUsed.' );
2355 }
2356
2357 $title = Title::newFromText( $pageName, $defaultNs );
2358 $page = WikiPage::factory( $title );
2359
2360 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
2361 }
2362
2363 /**
2364 * Revision-deletes a revision.
2365 *
2366 * @param Revision|int $rev Revision to delete
2367 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2368 * clear, -1 to leave alone. (All other values also clear the bit.)
2369 * @param string $comment Deletion comment
2370 */
2371 protected function revisionDelete(
2372 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
2373 ) {
2374 if ( is_int( $rev ) ) {
2375 $rev = Revision::newFromId( $rev );
2376 }
2377 RevisionDeleter::createList(
2378 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
2379 )->setVisibility( [
2380 'value' => $value,
2381 'comment' => $comment,
2382 ] );
2383 }
2384 }