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