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