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