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