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