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