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