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