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