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