Merge "Don't save and restore the interwiki table"
[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 * @var LoggerInterface
111 */
112 private $testLogger;
113
114 /**
115 * Table name prefixes. Oracle likes it shorter.
116 */
117 const DB_PREFIX = 'unittest_';
118 const ORA_DB_PREFIX = 'ut_';
119
120 /**
121 * @var array
122 * @since 1.18
123 */
124 protected $supportedDBs = [
125 'mysql',
126 'sqlite',
127 'postgres',
128 'oracle'
129 ];
130
131 public function __construct( $name = null, array $data = [], $dataName = '' ) {
132 parent::__construct( $name, $data, $dataName );
133
134 $this->backupGlobals = false;
135 $this->backupStaticAttributes = false;
136 $this->testLogger = self::getTestLogger();
137 }
138
139 private static function getTestLogger() {
140 return LoggerFactory::getInstance( 'tests-phpunit' );
141 }
142
143 public function __destruct() {
144 // Complain if self::setUp() was called, but not self::tearDown()
145 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
146 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
147 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
148 }
149 }
150
151 public static function setUpBeforeClass() {
152 parent::setUpBeforeClass();
153
154 // Get the original service locator
155 if ( !self::$originalServices ) {
156 self::$originalServices = MediaWikiServices::getInstance();
157 }
158 }
159
160 /**
161 * Convenience method for getting an immutable test user
162 *
163 * @since 1.28
164 *
165 * @param string[] $groups Groups the test user should be in.
166 * @return TestUser
167 */
168 public static function getTestUser( $groups = [] ) {
169 return TestUserRegistry::getImmutableTestUser( $groups );
170 }
171
172 /**
173 * Convenience method for getting a mutable test user
174 *
175 * @since 1.28
176 *
177 * @param string[] $groups Groups the test user should be added in.
178 * @return TestUser
179 */
180 public static function getMutableTestUser( $groups = [] ) {
181 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
182 }
183
184 /**
185 * Convenience method for getting an immutable admin test user
186 *
187 * @since 1.28
188 *
189 * @param string[] $groups Groups the test user should be added to.
190 * @return TestUser
191 */
192 public static function getTestSysop() {
193 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
194 }
195
196 /**
197 * Returns a WikiPage representing an existing page.
198 *
199 * @since 1.32
200 *
201 * @param Title|string|null $title
202 * @return WikiPage
203 * @throws MWException
204 */
205 protected function getExistingTestPage( $title = null ) {
206 $title = ( $title === null ) ? 'UTPage' : $title;
207 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
208 $page = WikiPage::factory( $title );
209
210 if ( !$page->exists() ) {
211 $user = self::getTestSysop()->getUser();
212 $page->doEditContent(
213 new WikitextContent( 'UTContent' ),
214 'UTPageSummary',
215 EDIT_NEW | EDIT_SUPPRESS_RC,
216 false,
217 $user
218 );
219 }
220
221 return $page;
222 }
223
224 /**
225 * Returns a WikiPage representing a non-existing page.
226 *
227 * @since 1.32
228 *
229 * @param Title|string|null $title
230 * @return WikiPage
231 * @throws MWException
232 */
233 protected function getNonexistingTestPage( $title = null ) {
234 $title = ( $title === null ) ? 'UTPage-' . rand( 0, 100000 ) : $title;
235 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
236 $page = WikiPage::factory( $title );
237
238 if ( $page->exists() ) {
239 $page->doDeleteArticle( 'Testing' );
240 }
241
242 return $page;
243 }
244
245 /**
246 * @deprecated since 1.32
247 */
248 public static function prepareServices( Config $bootstrapConfig ) {
249 }
250
251 /**
252 * Create a config suitable for testing, based on a base config, default overrides,
253 * and custom overrides.
254 *
255 * @param Config|null $baseConfig
256 * @param Config|null $customOverrides
257 *
258 * @return Config
259 */
260 private static function makeTestConfig(
261 Config $baseConfig = null,
262 Config $customOverrides = null
263 ) {
264 $defaultOverrides = new HashConfig();
265
266 if ( !$baseConfig ) {
267 $baseConfig = self::$originalServices->getBootstrapConfig();
268 }
269
270 /* Some functions require some kind of caching, and will end up using the db,
271 * which we can't allow, as that would open a new connection for mysql.
272 * Replace with a HashBag. They would not be going to persist anyway.
273 */
274 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
275 $objectCaches = [
276 CACHE_DB => $hashCache,
277 CACHE_ACCEL => $hashCache,
278 CACHE_MEMCACHED => $hashCache,
279 'apc' => $hashCache,
280 'apcu' => $hashCache,
281 'wincache' => $hashCache,
282 ] + $baseConfig->get( 'ObjectCaches' );
283
284 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
285 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
286 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory::class ] ] );
287
288 // Use a fast hash algorithm to hash passwords.
289 $defaultOverrides->set( 'PasswordDefault', 'A' );
290
291 $testConfig = $customOverrides
292 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
293 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
294
295 return $testConfig;
296 }
297
298 /**
299 * @param ConfigFactory $oldConfigFactory
300 * @param LBFactory $oldLoadBalancerFactory
301 * @param MediaWikiServices $newServices
302 *
303 * @throws MWException
304 */
305 private static function installTestServices(
306 ConfigFactory $oldConfigFactory,
307 LBFactory $oldLoadBalancerFactory,
308 MediaWikiServices $newServices
309 ) {
310 // Use bootstrap config for all configuration.
311 // This allows config overrides via global variables to take effect.
312 $bootstrapConfig = $newServices->getBootstrapConfig();
313 $newServices->resetServiceForTesting( 'ConfigFactory' );
314 $newServices->redefineService(
315 'ConfigFactory',
316 self::makeTestConfigFactoryInstantiator(
317 $oldConfigFactory,
318 [ 'main' => $bootstrapConfig ]
319 )
320 );
321 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
322 $newServices->redefineService(
323 'DBLoadBalancerFactory',
324 function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
325 return $oldLoadBalancerFactory;
326 }
327 );
328 }
329
330 /**
331 * @param ConfigFactory $oldFactory
332 * @param Config[] $configurations
333 *
334 * @return Closure
335 */
336 private static function makeTestConfigFactoryInstantiator(
337 ConfigFactory $oldFactory,
338 array $configurations
339 ) {
340 return function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
341 $factory = new ConfigFactory();
342
343 // clone configurations from $oldFactory that are not overwritten by $configurations
344 $namesToClone = array_diff(
345 $oldFactory->getConfigNames(),
346 array_keys( $configurations )
347 );
348
349 foreach ( $namesToClone as $name ) {
350 $factory->register( $name, $oldFactory->makeConfig( $name ) );
351 }
352
353 foreach ( $configurations as $name => $config ) {
354 $factory->register( $name, $config );
355 }
356
357 return $factory;
358 };
359 }
360
361 /**
362 * Resets some non-service singleton instances and other static caches. It's not necessary to
363 * reset services here.
364 */
365 private function resetNonServiceCaches() {
366 global $wgRequest, $wgJobClasses;
367
368 foreach ( $wgJobClasses as $type => $class ) {
369 JobQueueGroup::singleton()->get( $type )->delete();
370 }
371 JobQueueGroup::destroySingletons();
372
373 ObjectCache::clear();
374 FileBackendGroup::destroySingleton();
375 DeferredUpdates::clearPendingUpdates();
376
377 // TODO: move global state into MediaWikiServices
378 RequestContext::resetMain();
379 if ( session_id() !== '' ) {
380 session_write_close();
381 session_id( '' );
382 }
383
384 $wgRequest = new FauxRequest();
385 MediaWiki\Session\SessionManager::resetCache();
386 }
387
388 public function run( PHPUnit_Framework_TestResult $result = null ) {
389 $this->overrideMwServices();
390
391 $needsResetDB = false;
392
393 if ( !self::$dbSetup || $this->needsDB() ) {
394 // set up a DB connection for this test to use
395 $this->testLogger->info( "Setting up DB for " . $this->toString() );
396
397 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
398 self::$reuseDB = $this->getCliArg( 'reuse-db' );
399
400 $this->db = wfGetDB( DB_MASTER );
401
402 $this->checkDbIsSupported();
403
404 if ( !self::$dbSetup ) {
405 $this->setupAllTestDBs();
406 $this->addCoreDBData();
407 }
408
409 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
410 // is available in subclass's setUpBeforeClass() and setUp() methods.
411 // This would also remove the need for the HACK that is oncePerClass().
412 if ( $this->oncePerClass() ) {
413 $this->setUpSchema( $this->db );
414 $this->resetDB( $this->db, $this->tablesUsed );
415 $this->addDBDataOnce();
416 }
417
418 $this->addDBData();
419 $needsResetDB = true;
420 }
421
422 $this->testLogger->info( "Starting test " . $this->toString() );
423 parent::run( $result );
424 $this->testLogger->info( "Finished test " . $this->toString() );
425
426 if ( $needsResetDB ) {
427 $this->testLogger->info( "Resetting DB" );
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 if ( $this->tablesUsed ) {
1072 return true;
1073 }
1074
1075 // If the test class says it belongs to the Database group, it needs the database.
1076 // NOTE: This ONLY checks for the group in the class level doc comment.
1077 $rc = new ReflectionClass( $this );
1078 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
1079 return true;
1080 }
1081
1082 return false;
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 $this->testLogger->info( __METHOD__ );
1158 if ( $this->db->getType() == 'oracle' ) {
1159 # Insert 0 user to prevent FK violations
1160 # Anonymous user
1161 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1162 $this->db->insert( 'user', [
1163 'user_id' => 0,
1164 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
1165 }
1166
1167 # Insert 0 page to prevent FK violations
1168 # Blank page
1169 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1170 $this->db->insert( 'page', [
1171 'page_id' => 0,
1172 'page_namespace' => 0,
1173 'page_title' => ' ',
1174 'page_restrictions' => null,
1175 'page_is_redirect' => 0,
1176 'page_is_new' => 0,
1177 'page_random' => 0,
1178 'page_touched' => $this->db->timestamp(),
1179 'page_latest' => 0,
1180 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1181 }
1182 }
1183
1184 SiteStatsInit::doPlaceholderInit();
1185
1186 User::resetIdByNameCache();
1187
1188 // Make sysop user
1189 $user = static::getTestSysop()->getUser();
1190
1191 // Make 1 page with 1 revision
1192 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1193 if ( $page->getId() == 0 ) {
1194 $page->doEditContent(
1195 new WikitextContent( 'UTContent' ),
1196 'UTPageSummary',
1197 EDIT_NEW | EDIT_SUPPRESS_RC,
1198 false,
1199 $user
1200 );
1201 // an edit always attempt to purge backlink links such as history
1202 // pages. That is unnecessary.
1203 JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->delete();
1204 // WikiPages::doEditUpdates randomly adds RC purges
1205 JobQueueGroup::singleton()->get( 'recentChangesUpdate' )->delete();
1206
1207 // doEditContent() probably started the session via
1208 // User::loadFromSession(). Close it now.
1209 if ( session_id() !== '' ) {
1210 session_write_close();
1211 session_id( '' );
1212 }
1213 }
1214 }
1215
1216 /**
1217 * Restores MediaWiki to using the table set (table prefix) it was using before
1218 * setupTestDB() was called. Useful if we need to perform database operations
1219 * after the test run has finished (such as saving logs or profiling info).
1220 *
1221 * This is called by phpunit/bootstrap.php after the last test.
1222 *
1223 * @since 1.21
1224 */
1225 public static function teardownTestDB() {
1226 global $wgJobClasses;
1227
1228 if ( !self::$dbSetup ) {
1229 return;
1230 }
1231
1232 Hooks::run( 'UnitTestsBeforeDatabaseTeardown' );
1233
1234 foreach ( $wgJobClasses as $type => $class ) {
1235 // Delete any jobs under the clone DB (or old prefix in other stores)
1236 JobQueueGroup::singleton()->get( $type )->delete();
1237 }
1238
1239 CloneDatabase::changePrefix( self::$oldTablePrefix );
1240
1241 self::$oldTablePrefix = false;
1242 self::$dbSetup = false;
1243 }
1244
1245 /**
1246 * Prepares the given database connection for usage in the context of usage tests.
1247 * This sets up clones database tables and changes the table prefix as appropriate.
1248 * If the database connection already has cloned tables, calling this method has no
1249 * effect. The tables are not re-cloned or reset in that case.
1250 *
1251 * @param IMaintainableDatabase $db
1252 */
1253 protected function prepareConnectionForTesting( IMaintainableDatabase $db ) {
1254 if ( !self::$dbSetup ) {
1255 throw new LogicException(
1256 'Cannot use prepareConnectionForTesting()'
1257 . ' if the test case is not defined to use the database!'
1258 );
1259 }
1260
1261 if ( isset( $db->_originalTablePrefix ) ) {
1262 // The DB connection was already prepared for testing.
1263 return;
1264 }
1265
1266 $testPrefix = self::getTestPrefixFor( $db );
1267 $oldPrefix = $db->tablePrefix();
1268
1269 $tablesCloned = self::listTables( $db );
1270
1271 if ( $oldPrefix === $testPrefix ) {
1272 // The database connection already has the test prefix, but presumably not
1273 // the cloned tables. This is the typical case, since the LBFactory will
1274 // have the prefix set during testing, but LoadBalancers will still return
1275 // connections that don't have the cloned table structure.
1276 $oldPrefix = self::$oldTablePrefix;
1277 }
1278
1279 $dbClone = new CloneDatabase( $db, $tablesCloned, $testPrefix, $oldPrefix );
1280 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1281
1282 $db->_originalTablePrefix = $oldPrefix;
1283
1284 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1285 throw new LogicException( 'Cannot clone database tables' );
1286 } else {
1287 $dbClone->cloneTableStructure();
1288 }
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 // NOTE: Do not reset the slot_roles and content_models tables, but let them
1681 // leak across tests. Resetting them would require to reset all NamedTableStore
1682 // instances for these tables, of which there may be several beyond the ones
1683 // known to MediaWikiServices. See T202641.
1684 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1685 $pageTables = [
1686 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1687 'revision_actor_temp', 'slots', 'content',
1688 ];
1689 $coreDBDataTables = array_merge( $userTables, $pageTables );
1690
1691 // If any of the user or page tables were marked as used, we should clear all of them.
1692 if ( array_intersect( $tablesUsed, $userTables ) ) {
1693 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1694 TestUserRegistry::clear();
1695 }
1696 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1697 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1698 }
1699
1700 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1701 // instead of user/text. But Postgres does not remap the
1702 // table name in tableExists(), so we mark the real table
1703 // names as being used.
1704 if ( $db->getType() === 'postgres' ) {
1705 if ( in_array( 'user', $tablesUsed ) ) {
1706 $tablesUsed[] = 'mwuser';
1707 }
1708 if ( in_array( 'text', $tablesUsed ) ) {
1709 $tablesUsed[] = 'pagecontent';
1710 }
1711 }
1712
1713 foreach ( $tablesUsed as $tbl ) {
1714 $this->truncateTable( $tbl, $db );
1715 }
1716
1717 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1718 // Re-add core DB data that was deleted
1719 $this->addCoreDBData();
1720 }
1721 }
1722 }
1723
1724 /**
1725 * Empties the given table and resets any auto-increment counters.
1726 * Will also purge caches associated with some well known tables.
1727 * If the table is not know, this method just returns.
1728 *
1729 * @param string $tableName
1730 * @param IDatabase|null $db
1731 */
1732 protected function truncateTable( $tableName, IDatabase $db = null ) {
1733 if ( !$db ) {
1734 $db = $this->db;
1735 }
1736
1737 if ( !$db->tableExists( $tableName ) ) {
1738 return;
1739 }
1740
1741 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1742
1743 if ( $truncate ) {
1744 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__ );
1745 } else {
1746 $db->delete( $tableName, '*', __METHOD__ );
1747 }
1748
1749 if ( in_array( $db->getType(), [ 'postgres', 'sqlite' ], true ) ) {
1750 // Reset the table's sequence too.
1751 $db->resetSequenceForTable( $tableName, __METHOD__ );
1752 }
1753 }
1754
1755 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1756 $tableName = substr( $tableName, strlen( $prefix ) );
1757 }
1758
1759 private static function isNotUnittest( $table ) {
1760 return strpos( $table, self::DB_PREFIX ) !== 0;
1761 }
1762
1763 /**
1764 * @since 1.18
1765 *
1766 * @param IMaintainableDatabase $db
1767 *
1768 * @return array
1769 */
1770 public static function listTables( IMaintainableDatabase $db ) {
1771 $prefix = $db->tablePrefix();
1772 $tables = $db->listTables( $prefix, __METHOD__ );
1773
1774 if ( $db->getType() === 'mysql' ) {
1775 static $viewListCache = null;
1776 if ( $viewListCache === null ) {
1777 $viewListCache = $db->listViews( null, __METHOD__ );
1778 }
1779 // T45571: cannot clone VIEWs under MySQL
1780 $tables = array_diff( $tables, $viewListCache );
1781 }
1782 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1783
1784 // Don't duplicate test tables from the previous fataled run
1785 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1786
1787 if ( $db->getType() == 'sqlite' ) {
1788 $tables = array_flip( $tables );
1789 // these are subtables of searchindex and don't need to be duped/dropped separately
1790 unset( $tables['searchindex_content'] );
1791 unset( $tables['searchindex_segdir'] );
1792 unset( $tables['searchindex_segments'] );
1793 $tables = array_flip( $tables );
1794 }
1795
1796 return $tables;
1797 }
1798
1799 /**
1800 * Copy test data from one database connection to another.
1801 *
1802 * This should only be used for small data sets.
1803 *
1804 * @param IDatabase $source
1805 * @param IDatabase $target
1806 */
1807 public function copyTestData( IDatabase $source, IDatabase $target ) {
1808 $tables = self::listOriginalTables( $source, 'unprefixed' );
1809
1810 foreach ( $tables as $table ) {
1811 $res = $source->select( $table, '*', [], __METHOD__ );
1812 $allRows = [];
1813
1814 foreach ( $res as $row ) {
1815 $allRows[] = (array)$row;
1816 }
1817
1818 $target->insert( $table, $allRows, __METHOD__, [ 'IGNORE' ] );
1819 }
1820 }
1821
1822 /**
1823 * @throws MWException
1824 * @since 1.18
1825 */
1826 protected function checkDbIsSupported() {
1827 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1828 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1829 }
1830 }
1831
1832 /**
1833 * @since 1.18
1834 * @param string $offset
1835 * @return mixed
1836 */
1837 public function getCliArg( $offset ) {
1838 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1839 return PHPUnitMaintClass::$additionalOptions[$offset];
1840 }
1841
1842 return null;
1843 }
1844
1845 /**
1846 * @since 1.18
1847 * @param string $offset
1848 * @param mixed $value
1849 */
1850 public function setCliArg( $offset, $value ) {
1851 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1852 }
1853
1854 /**
1855 * Don't throw a warning if $function is deprecated and called later
1856 *
1857 * @since 1.19
1858 *
1859 * @param string $function
1860 */
1861 public function hideDeprecated( $function ) {
1862 Wikimedia\suppressWarnings();
1863 wfDeprecated( $function );
1864 Wikimedia\restoreWarnings();
1865 }
1866
1867 /**
1868 * Asserts that the given database query yields the rows given by $expectedRows.
1869 * The expected rows should be given as indexed (not associative) arrays, with
1870 * the values given in the order of the columns in the $fields parameter.
1871 * Note that the rows are sorted by the columns given in $fields.
1872 *
1873 * @since 1.20
1874 *
1875 * @param string|array $table The table(s) to query
1876 * @param string|array $fields The columns to include in the result (and to sort by)
1877 * @param string|array $condition "where" condition(s)
1878 * @param array $expectedRows An array of arrays giving the expected rows.
1879 * @param array $options Options for the query
1880 * @param array $join_conds Join conditions for the query
1881 *
1882 * @throws MWException If this test cases's needsDB() method doesn't return true.
1883 * Test cases can use "@group Database" to enable database test support,
1884 * or list the tables under testing in $this->tablesUsed, or override the
1885 * needsDB() method.
1886 */
1887 protected function assertSelect(
1888 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1889 ) {
1890 if ( !$this->needsDB() ) {
1891 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1892 ' method should return true. Use @group Database or $this->tablesUsed.' );
1893 }
1894
1895 $db = wfGetDB( DB_REPLICA );
1896
1897 $res = $db->select(
1898 $table,
1899 $fields,
1900 $condition,
1901 wfGetCaller(),
1902 $options + [ 'ORDER BY' => $fields ],
1903 $join_conds
1904 );
1905 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1906
1907 $i = 0;
1908
1909 foreach ( $expectedRows as $expected ) {
1910 $r = $res->fetchRow();
1911 self::stripStringKeys( $r );
1912
1913 $i += 1;
1914 $this->assertNotEmpty( $r, "row #$i missing" );
1915
1916 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1917 }
1918
1919 $r = $res->fetchRow();
1920 self::stripStringKeys( $r );
1921
1922 $this->assertFalse( $r, "found extra row (after #$i)" );
1923 }
1924
1925 /**
1926 * Utility method taking an array of elements and wrapping
1927 * each element in its own array. Useful for data providers
1928 * that only return a single argument.
1929 *
1930 * @since 1.20
1931 *
1932 * @param array $elements
1933 *
1934 * @return array
1935 */
1936 protected function arrayWrap( array $elements ) {
1937 return array_map(
1938 function ( $element ) {
1939 return [ $element ];
1940 },
1941 $elements
1942 );
1943 }
1944
1945 /**
1946 * Assert that two arrays are equal. By default this means that both arrays need to hold
1947 * the same set of values. Using additional arguments, order and associated key can also
1948 * be set as relevant.
1949 *
1950 * @since 1.20
1951 *
1952 * @param array $expected
1953 * @param array $actual
1954 * @param bool $ordered If the order of the values should match
1955 * @param bool $named If the keys should match
1956 */
1957 protected function assertArrayEquals( array $expected, array $actual,
1958 $ordered = false, $named = false
1959 ) {
1960 if ( !$ordered ) {
1961 $this->objectAssociativeSort( $expected );
1962 $this->objectAssociativeSort( $actual );
1963 }
1964
1965 if ( !$named ) {
1966 $expected = array_values( $expected );
1967 $actual = array_values( $actual );
1968 }
1969
1970 call_user_func_array(
1971 [ $this, 'assertEquals' ],
1972 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1973 );
1974 }
1975
1976 /**
1977 * Put each HTML element on its own line and then equals() the results
1978 *
1979 * Use for nicely formatting of PHPUnit diff output when comparing very
1980 * simple HTML
1981 *
1982 * @since 1.20
1983 *
1984 * @param string $expected HTML on oneline
1985 * @param string $actual HTML on oneline
1986 * @param string $msg Optional message
1987 */
1988 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1989 $expected = str_replace( '>', ">\n", $expected );
1990 $actual = str_replace( '>', ">\n", $actual );
1991
1992 $this->assertEquals( $expected, $actual, $msg );
1993 }
1994
1995 /**
1996 * Does an associative sort that works for objects.
1997 *
1998 * @since 1.20
1999 *
2000 * @param array &$array
2001 */
2002 protected function objectAssociativeSort( array &$array ) {
2003 uasort(
2004 $array,
2005 function ( $a, $b ) {
2006 return serialize( $a ) <=> serialize( $b );
2007 }
2008 );
2009 }
2010
2011 /**
2012 * Utility function for eliminating all string keys from an array.
2013 * Useful to turn a database result row as returned by fetchRow() into
2014 * a pure indexed array.
2015 *
2016 * @since 1.20
2017 *
2018 * @param mixed &$r The array to remove string keys from.
2019 */
2020 protected static function stripStringKeys( &$r ) {
2021 if ( !is_array( $r ) ) {
2022 return;
2023 }
2024
2025 foreach ( $r as $k => $v ) {
2026 if ( is_string( $k ) ) {
2027 unset( $r[$k] );
2028 }
2029 }
2030 }
2031
2032 /**
2033 * Asserts that the provided variable is of the specified
2034 * internal type or equals the $value argument. This is useful
2035 * for testing return types of functions that return a certain
2036 * type or *value* when not set or on error.
2037 *
2038 * @since 1.20
2039 *
2040 * @param string $type
2041 * @param mixed $actual
2042 * @param mixed $value
2043 * @param string $message
2044 */
2045 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2046 if ( $actual === $value ) {
2047 $this->assertTrue( true, $message );
2048 } else {
2049 $this->assertType( $type, $actual, $message );
2050 }
2051 }
2052
2053 /**
2054 * Asserts the type of the provided value. This can be either
2055 * in internal type such as boolean or integer, or a class or
2056 * interface the value extends or implements.
2057 *
2058 * @since 1.20
2059 *
2060 * @param string $type
2061 * @param mixed $actual
2062 * @param string $message
2063 */
2064 protected function assertType( $type, $actual, $message = '' ) {
2065 if ( class_exists( $type ) || interface_exists( $type ) ) {
2066 $this->assertInstanceOf( $type, $actual, $message );
2067 } else {
2068 $this->assertInternalType( $type, $actual, $message );
2069 }
2070 }
2071
2072 /**
2073 * Returns true if the given namespace defaults to Wikitext
2074 * according to $wgNamespaceContentModels
2075 *
2076 * @param int $ns The namespace ID to check
2077 *
2078 * @return bool
2079 * @since 1.21
2080 */
2081 protected function isWikitextNS( $ns ) {
2082 global $wgNamespaceContentModels;
2083
2084 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2085 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2086 }
2087
2088 return true;
2089 }
2090
2091 /**
2092 * Returns the ID of a namespace that defaults to Wikitext.
2093 *
2094 * @throws MWException If there is none.
2095 * @return int The ID of the wikitext Namespace
2096 * @since 1.21
2097 */
2098 protected function getDefaultWikitextNS() {
2099 global $wgNamespaceContentModels;
2100
2101 static $wikitextNS = null; // this is not going to change
2102 if ( $wikitextNS !== null ) {
2103 return $wikitextNS;
2104 }
2105
2106 // quickly short out on most common case:
2107 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2108 return NS_MAIN;
2109 }
2110
2111 // NOTE: prefer content namespaces
2112 $namespaces = array_unique( array_merge(
2113 MWNamespace::getContentNamespaces(),
2114 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2115 MWNamespace::getValidNamespaces()
2116 ) );
2117
2118 $namespaces = array_diff( $namespaces, [
2119 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2120 ] );
2121
2122 $talk = array_filter( $namespaces, function ( $ns ) {
2123 return MWNamespace::isTalk( $ns );
2124 } );
2125
2126 // prefer non-talk pages
2127 $namespaces = array_diff( $namespaces, $talk );
2128 $namespaces = array_merge( $namespaces, $talk );
2129
2130 // check default content model of each namespace
2131 foreach ( $namespaces as $ns ) {
2132 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2133 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2134 ) {
2135 $wikitextNS = $ns;
2136
2137 return $wikitextNS;
2138 }
2139 }
2140
2141 // give up
2142 // @todo Inside a test, we could skip the test as incomplete.
2143 // But frequently, this is used in fixture setup.
2144 throw new MWException( "No namespace defaults to wikitext!" );
2145 }
2146
2147 /**
2148 * Check, if $wgDiff3 is set and ready to merge
2149 * Will mark the calling test as skipped, if not ready
2150 *
2151 * @since 1.21
2152 */
2153 protected function markTestSkippedIfNoDiff3() {
2154 global $wgDiff3;
2155
2156 # This check may also protect against code injection in
2157 # case of broken installations.
2158 Wikimedia\suppressWarnings();
2159 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2160 Wikimedia\restoreWarnings();
2161
2162 if ( !$haveDiff3 ) {
2163 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2164 }
2165 }
2166
2167 /**
2168 * Check if $extName is a loaded PHP extension, will skip the
2169 * test whenever it is not loaded.
2170 *
2171 * @since 1.21
2172 * @param string $extName
2173 * @return bool
2174 */
2175 protected function checkPHPExtension( $extName ) {
2176 $loaded = extension_loaded( $extName );
2177 if ( !$loaded ) {
2178 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2179 }
2180
2181 return $loaded;
2182 }
2183
2184 /**
2185 * Skip the test if using the specified database type
2186 *
2187 * @param string $type Database type
2188 * @since 1.32
2189 */
2190 protected function markTestSkippedIfDbType( $type ) {
2191 if ( $this->db->getType() === $type ) {
2192 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2193 }
2194 }
2195
2196 /**
2197 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2198 * @param string $buffer
2199 * @return string
2200 */
2201 public static function wfResetOutputBuffersBarrier( $buffer ) {
2202 return $buffer;
2203 }
2204
2205 /**
2206 * Create a temporary hook handler which will be reset by tearDown.
2207 * This replaces other handlers for the same hook.
2208 * @param string $hookName Hook name
2209 * @param mixed $handler Value suitable for a hook handler
2210 * @since 1.28
2211 */
2212 protected function setTemporaryHook( $hookName, $handler ) {
2213 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2214 }
2215
2216 /**
2217 * Check whether file contains given data.
2218 * @param string $fileName
2219 * @param string $actualData
2220 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2221 * and skip the test.
2222 * @param string $msg
2223 * @since 1.30
2224 */
2225 protected function assertFileContains(
2226 $fileName,
2227 $actualData,
2228 $createIfMissing = true,
2229 $msg = ''
2230 ) {
2231 if ( $createIfMissing ) {
2232 if ( !file_exists( $fileName ) ) {
2233 file_put_contents( $fileName, $actualData );
2234 $this->markTestSkipped( 'Data file $fileName does not exist' );
2235 }
2236 } else {
2237 self::assertFileExists( $fileName );
2238 }
2239 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2240 }
2241
2242 /**
2243 * Edits or creates a page/revision
2244 * @param string $pageName Page title
2245 * @param string $text Content of the page
2246 * @param string $summary Optional summary string for the revision
2247 * @param int $defaultNs Optional namespace id
2248 * @return array Array as returned by WikiPage::doEditContent()
2249 */
2250 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
2251 $title = Title::newFromText( $pageName, $defaultNs );
2252 $page = WikiPage::factory( $title );
2253
2254 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
2255 }
2256
2257 /**
2258 * Revision-deletes a revision.
2259 *
2260 * @param Revision|int $rev Revision to delete
2261 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2262 * clear, -1 to leave alone. (All other values also clear the bit.)
2263 * @param string $comment Deletion comment
2264 */
2265 protected function revisionDelete(
2266 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
2267 ) {
2268 if ( is_int( $rev ) ) {
2269 $rev = Revision::newFromId( $rev );
2270 }
2271 RevisionDeleter::createList(
2272 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
2273 )->setVisibility( [
2274 'value' => $value,
2275 'comment' => $comment,
2276 ] );
2277 }
2278 }