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