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