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