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