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