Merge "Revert "Don't construct SpecialPages twice""
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2 use MediaWiki\Logger\LegacySpi;
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\MonologSpi;
5 use MediaWiki\MediaWikiServices;
6 use Psr\Log\LoggerInterface;
7
8 /**
9 * @since 1.18
10 */
11 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
12
13 /**
14 * The service locator created by prepareServices(). This service locator will
15 * be restored after each test. Tests that pollute the global service locator
16 * instance should use overrideMwServices() to isolate the test.
17 *
18 * @var MediaWikiServices|null
19 */
20 private static $serviceLocator = null;
21
22 /**
23 * $called tracks whether the setUp and tearDown method has been called.
24 * class extending MediaWikiTestCase usually override setUp and tearDown
25 * but forget to call the parent.
26 *
27 * The array format takes a method name as key and anything as a value.
28 * By asserting the key exist, we know the child class has called the
29 * parent.
30 *
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
33 */
34 private $called = [];
35
36 /**
37 * @var TestUser[]
38 * @since 1.20
39 */
40 public static $users;
41
42 /**
43 * Primary database
44 *
45 * @var Database
46 * @since 1.18
47 */
48 protected $db;
49
50 /**
51 * @var array
52 * @since 1.19
53 */
54 protected $tablesUsed = []; // tables with data
55
56 private static $useTemporaryTables = true;
57 private static $reuseDB = false;
58 private static $dbSetup = false;
59 private static $oldTablePrefix = '';
60
61 /**
62 * Original value of PHP's error_reporting setting.
63 *
64 * @var int
65 */
66 private $phpErrorLevel;
67
68 /**
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
71 *
72 * @var array
73 */
74 private $tmpFiles = [];
75
76 /**
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
80 * @var array
81 */
82 private $mwGlobals = [];
83
84 /**
85 * Holds original loggers which have been replaced by setLogger()
86 * @var LoggerInterface[]
87 */
88 private $loggers = [];
89
90 /**
91 * Table name prefixes. Oracle likes it shorter.
92 */
93 const DB_PREFIX = 'unittest_';
94 const ORA_DB_PREFIX = 'ut_';
95
96 /**
97 * @var array
98 * @since 1.18
99 */
100 protected $supportedDBs = [
101 'mysql',
102 'sqlite',
103 'postgres',
104 'oracle'
105 ];
106
107 public function __construct( $name = null, array $data = [], $dataName = '' ) {
108 parent::__construct( $name, $data, $dataName );
109
110 $this->backupGlobals = false;
111 $this->backupStaticAttributes = false;
112 }
113
114 public function __destruct() {
115 // Complain if self::setUp() was called, but not self::tearDown()
116 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
117 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
118 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
119 }
120 }
121
122 public static function setUpBeforeClass() {
123 parent::setUpBeforeClass();
124
125 // Get the service locator, and reset services if it's not done already
126 self::$serviceLocator = self::prepareServices( new GlobalVarConfig() );
127 }
128
129 /**
130 * Convenience method for getting an immutable test user
131 *
132 * @since 1.28
133 *
134 * @param string[] $groups Groups the test user should be in.
135 * @return TestUser
136 */
137 public static function getTestUser( $groups = [] ) {
138 return TestUserRegistry::getImmutableTestUser( $groups );
139 }
140
141 /**
142 * Convenience method for getting a mutable test user
143 *
144 * @since 1.28
145 *
146 * @param string[] $groups Groups the test user should be added in.
147 * @return TestUser
148 */
149 public static function getMutableTestUser( $groups = [] ) {
150 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
151 }
152
153 /**
154 * Convenience method for getting an immutable admin test user
155 *
156 * @since 1.28
157 *
158 * @param string[] $groups Groups the test user should be added to.
159 * @return TestUser
160 */
161 public static function getTestSysop() {
162 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
163 }
164
165 /**
166 * Prepare service configuration for unit testing.
167 *
168 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
169 * to be overridden for testing.
170 *
171 * prepareServices() only needs to be called once, but should be called as early as possible,
172 * before any class has a chance to grab a reference to any of the global services
173 * instances that get discarded by prepareServices(). Only the first call has any effect,
174 * later calls are ignored.
175 *
176 * @note This is called by PHPUnitMaintClass::finalSetup.
177 *
178 * @see MediaWikiServices::resetGlobalInstance()
179 *
180 * @param Config $bootstrapConfig The bootstrap config to use with the new
181 * MediaWikiServices. Only used for the first call to this method.
182 * @return MediaWikiServices
183 */
184 public static function prepareServices( Config $bootstrapConfig ) {
185 static $services = null;
186
187 if ( !$services ) {
188 $services = self::resetGlobalServices( $bootstrapConfig );
189 }
190 return $services;
191 }
192
193 /**
194 * Reset global services, and install testing environment.
195 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
196 * This should only be used to set up the testing environment, not when
197 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
198 *
199 * @see MediaWikiServices::resetGlobalInstance()
200 * @see prepareServices()
201 * @see MediaWikiTestCase::overrideMwServices()
202 *
203 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
204 * MediaWikiServices.
205 */
206 protected static function resetGlobalServices( Config $bootstrapConfig = null ) {
207 $oldServices = MediaWikiServices::getInstance();
208 $oldConfigFactory = $oldServices->getConfigFactory();
209
210 $testConfig = self::makeTestConfig( $bootstrapConfig );
211
212 MediaWikiServices::resetGlobalInstance( $testConfig );
213
214 $serviceLocator = MediaWikiServices::getInstance();
215 self::installTestServices(
216 $oldConfigFactory,
217 $serviceLocator
218 );
219 return $serviceLocator;
220 }
221
222 /**
223 * Create a config suitable for testing, based on a base config, default overrides,
224 * and custom overrides.
225 *
226 * @param Config|null $baseConfig
227 * @param Config|null $customOverrides
228 *
229 * @return Config
230 */
231 private static function makeTestConfig(
232 Config $baseConfig = null,
233 Config $customOverrides = null
234 ) {
235 $defaultOverrides = new HashConfig();
236
237 if ( !$baseConfig ) {
238 $baseConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
239 }
240
241 /* Some functions require some kind of caching, and will end up using the db,
242 * which we can't allow, as that would open a new connection for mysql.
243 * Replace with a HashBag. They would not be going to persist anyway.
244 */
245 $hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
246 $objectCaches = [
247 CACHE_DB => $hashCache,
248 CACHE_ACCEL => $hashCache,
249 CACHE_MEMCACHED => $hashCache,
250 'apc' => $hashCache,
251 'xcache' => $hashCache,
252 'wincache' => $hashCache,
253 ] + $baseConfig->get( 'ObjectCaches' );
254
255 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
256 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
257 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
258
259 // Use a fast hash algorithm to hash passwords.
260 $defaultOverrides->set( 'PasswordDefault', 'A' );
261
262 $testConfig = $customOverrides
263 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
264 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
265
266 return $testConfig;
267 }
268
269 /**
270 * @param ConfigFactory $oldConfigFactory
271 * @param MediaWikiServices $newServices
272 *
273 * @throws MWException
274 */
275 private static function installTestServices(
276 ConfigFactory $oldConfigFactory,
277 MediaWikiServices $newServices
278 ) {
279 // Use bootstrap config for all configuration.
280 // This allows config overrides via global variables to take effect.
281 $bootstrapConfig = $newServices->getBootstrapConfig();
282 $newServices->resetServiceForTesting( 'ConfigFactory' );
283 $newServices->redefineService(
284 'ConfigFactory',
285 self::makeTestConfigFactoryInstantiator(
286 $oldConfigFactory,
287 [ 'main' => $bootstrapConfig ]
288 )
289 );
290 }
291
292 /**
293 * @param ConfigFactory $oldFactory
294 * @param Config[] $configurations
295 *
296 * @return Closure
297 */
298 private static function makeTestConfigFactoryInstantiator(
299 ConfigFactory $oldFactory,
300 array $configurations
301 ) {
302 return function( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
303 $factory = new ConfigFactory();
304
305 // clone configurations from $oldFactory that are not overwritten by $configurations
306 $namesToClone = array_diff(
307 $oldFactory->getConfigNames(),
308 array_keys( $configurations )
309 );
310
311 foreach ( $namesToClone as $name ) {
312 $factory->register( $name, $oldFactory->makeConfig( $name ) );
313 }
314
315 foreach ( $configurations as $name => $config ) {
316 $factory->register( $name, $config );
317 }
318
319 return $factory;
320 };
321 }
322
323 /**
324 * Resets some well known services that typically have state that may interfere with unit tests.
325 * This is a lightweight alternative to resetGlobalServices().
326 *
327 * @note There is no guarantee that no references remain to stale service instances destroyed
328 * by a call to doLightweightServiceReset().
329 *
330 * @throws MWException if called outside of PHPUnit tests.
331 *
332 * @see resetGlobalServices()
333 */
334 private function doLightweightServiceReset() {
335 global $wgRequest;
336
337 JobQueueGroup::destroySingletons();
338 ObjectCache::clear();
339 $services = MediaWikiServices::getInstance();
340 $services->resetServiceForTesting( 'MainObjectStash' );
341 $services->resetServiceForTesting( 'LocalServerObjectCache' );
342 $services->getMainWANObjectCache()->clearProcessCache();
343 FileBackendGroup::destroySingleton();
344
345 // TODO: move global state into MediaWikiServices
346 RequestContext::resetMain();
347 if ( session_id() !== '' ) {
348 session_write_close();
349 session_id( '' );
350 }
351
352 $wgRequest = new FauxRequest();
353 MediaWiki\Session\SessionManager::resetCache();
354 }
355
356 public function run( PHPUnit_Framework_TestResult $result = null ) {
357 // Reset all caches between tests.
358 $this->doLightweightServiceReset();
359
360 $needsResetDB = false;
361
362 if ( !self::$dbSetup || $this->needsDB() ) {
363 // set up a DB connection for this test to use
364
365 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
366 self::$reuseDB = $this->getCliArg( 'reuse-db' );
367
368 $this->db = wfGetDB( DB_MASTER );
369
370 $this->checkDbIsSupported();
371
372 if ( !self::$dbSetup ) {
373 $this->setupAllTestDBs();
374 $this->addCoreDBData();
375
376 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
377 $this->resetDB( $this->db, $this->tablesUsed );
378 }
379 }
380
381 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
382 // is available in subclass's setUpBeforeClass() and setUp() methods.
383 // This would also remove the need for the HACK that is oncePerClass().
384 if ( $this->oncePerClass() ) {
385 $this->addDBDataOnce();
386 }
387
388 $this->addDBData();
389 $needsResetDB = true;
390 }
391
392 parent::run( $result );
393
394 if ( $needsResetDB ) {
395 $this->resetDB( $this->db, $this->tablesUsed );
396 }
397 }
398
399 /**
400 * @return bool
401 */
402 private function oncePerClass() {
403 // Remember current test class in the database connection,
404 // so we know when we need to run addData.
405
406 $class = static::class;
407
408 $first = !isset( $this->db->_hasDataForTestClass )
409 || $this->db->_hasDataForTestClass !== $class;
410
411 $this->db->_hasDataForTestClass = $class;
412 return $first;
413 }
414
415 /**
416 * @since 1.21
417 *
418 * @return bool
419 */
420 public function usesTemporaryTables() {
421 return self::$useTemporaryTables;
422 }
423
424 /**
425 * Obtains a new temporary file name
426 *
427 * The obtained filename is enlisted to be removed upon tearDown
428 *
429 * @since 1.20
430 *
431 * @return string Absolute name of the temporary file
432 */
433 protected function getNewTempFile() {
434 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
435 $this->tmpFiles[] = $fileName;
436
437 return $fileName;
438 }
439
440 /**
441 * obtains a new temporary directory
442 *
443 * The obtained directory is enlisted to be removed (recursively with all its contained
444 * files) upon tearDown.
445 *
446 * @since 1.20
447 *
448 * @return string Absolute name of the temporary directory
449 */
450 protected function getNewTempDirectory() {
451 // Starting of with a temporary /file/.
452 $fileName = $this->getNewTempFile();
453
454 // Converting the temporary /file/ to a /directory/
455 // The following is not atomic, but at least we now have a single place,
456 // where temporary directory creation is bundled and can be improved
457 unlink( $fileName );
458 $this->assertTrue( wfMkdirParents( $fileName ) );
459
460 return $fileName;
461 }
462
463 protected function setUp() {
464 parent::setUp();
465 $this->called['setUp'] = true;
466
467 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
468
469 // Cleaning up temporary files
470 foreach ( $this->tmpFiles as $fileName ) {
471 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
472 unlink( $fileName );
473 } elseif ( is_dir( $fileName ) ) {
474 wfRecursiveRemoveDir( $fileName );
475 }
476 }
477
478 if ( $this->needsDB() && $this->db ) {
479 // Clean up open transactions
480 while ( $this->db->trxLevel() > 0 ) {
481 $this->db->rollback( __METHOD__, 'flush' );
482 }
483 // Check for unsafe queries
484 if ( $this->db->getType() === 'mysql' ) {
485 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
486 }
487 }
488
489 DeferredUpdates::clearPendingUpdates();
490 ObjectCache::getMainWANInstance()->clearProcessCache();
491
492 // XXX: reset maintenance triggers
493 // Hook into period lag checks which often happen in long-running scripts
494 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
495 Maintenance::setLBFactoryTriggers( $lbFactory );
496
497 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
498 }
499
500 protected function addTmpFiles( $files ) {
501 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
502 }
503
504 protected function tearDown() {
505 global $wgRequest, $wgSQLMode;
506
507 $status = ob_get_status();
508 if ( isset( $status['name'] ) &&
509 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
510 ) {
511 ob_end_flush();
512 }
513
514 $this->called['tearDown'] = true;
515 // Cleaning up temporary files
516 foreach ( $this->tmpFiles as $fileName ) {
517 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
518 unlink( $fileName );
519 } elseif ( is_dir( $fileName ) ) {
520 wfRecursiveRemoveDir( $fileName );
521 }
522 }
523
524 if ( $this->needsDB() && $this->db ) {
525 // Clean up open transactions
526 while ( $this->db->trxLevel() > 0 ) {
527 $this->db->rollback( __METHOD__, 'flush' );
528 }
529 if ( $this->db->getType() === 'mysql' ) {
530 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ) );
531 }
532 }
533
534 // Restore mw globals
535 foreach ( $this->mwGlobals as $key => $value ) {
536 $GLOBALS[$key] = $value;
537 }
538 $this->mwGlobals = [];
539 $this->restoreLoggers();
540
541 if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
542 MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
543 }
544
545 // TODO: move global state into MediaWikiServices
546 RequestContext::resetMain();
547 if ( session_id() !== '' ) {
548 session_write_close();
549 session_id( '' );
550 }
551 $wgRequest = new FauxRequest();
552 MediaWiki\Session\SessionManager::resetCache();
553 MediaWiki\Auth\AuthManager::resetCache();
554
555 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
556
557 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
558 ini_set( 'error_reporting', $this->phpErrorLevel );
559
560 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
561 $newHex = strtoupper( dechex( $phpErrorLevel ) );
562 $message = "PHP error_reporting setting was left dirty: "
563 . "was 0x$oldHex before test, 0x$newHex after test!";
564
565 $this->fail( $message );
566 }
567
568 parent::tearDown();
569 }
570
571 /**
572 * Make sure MediaWikiTestCase extending classes have called their
573 * parent setUp method
574 */
575 final public function testMediaWikiTestCaseParentSetupCalled() {
576 $this->assertArrayHasKey( 'setUp', $this->called,
577 static::class . '::setUp() must call parent::setUp()'
578 );
579 }
580
581 /**
582 * Sets a service, maintaining a stashed version of the previous service to be
583 * restored in tearDown
584 *
585 * @since 1.27
586 *
587 * @param string $name
588 * @param object $object
589 */
590 protected function setService( $name, $object ) {
591 // If we did not yet override the service locator, so so now.
592 if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
593 $this->overrideMwServices();
594 }
595
596 MediaWikiServices::getInstance()->disableService( $name );
597 MediaWikiServices::getInstance()->redefineService(
598 $name,
599 function () use ( $object ) {
600 return $object;
601 }
602 );
603 }
604
605 /**
606 * Sets a global, maintaining a stashed version of the previous global to be
607 * restored in tearDown
608 *
609 * The key is added to the array of globals that will be reset afterwards
610 * in the tearDown().
611 *
612 * @example
613 * <code>
614 * protected function setUp() {
615 * $this->setMwGlobals( 'wgRestrictStuff', true );
616 * }
617 *
618 * function testFoo() {}
619 *
620 * function testBar() {}
621 * $this->assertTrue( self::getX()->doStuff() );
622 *
623 * $this->setMwGlobals( 'wgRestrictStuff', false );
624 * $this->assertTrue( self::getX()->doStuff() );
625 * }
626 *
627 * function testQuux() {}
628 * </code>
629 *
630 * @param array|string $pairs Key to the global variable, or an array
631 * of key/value pairs.
632 * @param mixed $value Value to set the global to (ignored
633 * if an array is given as first argument).
634 *
635 * @note To allow changes to global variables to take effect on global service instances,
636 * call overrideMwServices().
637 *
638 * @since 1.21
639 */
640 protected function setMwGlobals( $pairs, $value = null ) {
641 if ( is_string( $pairs ) ) {
642 $pairs = [ $pairs => $value ];
643 }
644
645 $this->stashMwGlobals( array_keys( $pairs ) );
646
647 foreach ( $pairs as $key => $value ) {
648 $GLOBALS[$key] = $value;
649 }
650 }
651
652 /**
653 * Check if we can back up a value by performing a shallow copy.
654 * Values which fail this test are copied recursively.
655 *
656 * @param mixed $value
657 * @return bool True if a shallow copy will do; false if a deep copy
658 * is required.
659 */
660 private static function canShallowCopy( $value ) {
661 if ( is_scalar( $value ) || $value === null ) {
662 return true;
663 }
664 if ( is_array( $value ) ) {
665 foreach ( $value as $subValue ) {
666 if ( !is_scalar( $subValue ) && $subValue !== null ) {
667 return false;
668 }
669 }
670 return true;
671 }
672 return false;
673 }
674
675 /**
676 * Stashes the global, will be restored in tearDown()
677 *
678 * Individual test functions may override globals through the setMwGlobals() function
679 * or directly. When directly overriding globals their keys should first be passed to this
680 * method in setUp to avoid breaking global state for other tests
681 *
682 * That way all other tests are executed with the same settings (instead of using the
683 * unreliable local settings for most tests and fix it only for some tests).
684 *
685 * @param array|string $globalKeys Key to the global variable, or an array of keys.
686 *
687 * @throws Exception When trying to stash an unset global
688 *
689 * @note To allow changes to global variables to take effect on global service instances,
690 * call overrideMwServices().
691 *
692 * @since 1.23
693 */
694 protected function stashMwGlobals( $globalKeys ) {
695 if ( is_string( $globalKeys ) ) {
696 $globalKeys = [ $globalKeys ];
697 }
698
699 foreach ( $globalKeys as $globalKey ) {
700 // NOTE: make sure we only save the global once or a second call to
701 // setMwGlobals() on the same global would override the original
702 // value.
703 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
704 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
705 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
706 }
707 // NOTE: we serialize then unserialize the value in case it is an object
708 // this stops any objects being passed by reference. We could use clone
709 // and if is_object but this does account for objects within objects!
710 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
711 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
712 } elseif (
713 // Many MediaWiki types are safe to clone. These are the
714 // ones that are most commonly stashed.
715 $GLOBALS[$globalKey] instanceof Language ||
716 $GLOBALS[$globalKey] instanceof User ||
717 $GLOBALS[$globalKey] instanceof FauxRequest
718 ) {
719 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
720 } else {
721 try {
722 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
723 } catch ( Exception $e ) {
724 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
725 }
726 }
727 }
728 }
729 }
730
731 /**
732 * Merges the given values into a MW global array variable.
733 * Useful for setting some entries in a configuration array, instead of
734 * setting the entire array.
735 *
736 * @param string $name The name of the global, as in wgFooBar
737 * @param array $values The array containing the entries to set in that global
738 *
739 * @throws MWException If the designated global is not an array.
740 *
741 * @note To allow changes to global variables to take effect on global service instances,
742 * call overrideMwServices().
743 *
744 * @since 1.21
745 */
746 protected function mergeMwGlobalArrayValue( $name, $values ) {
747 if ( !isset( $GLOBALS[$name] ) ) {
748 $merged = $values;
749 } else {
750 if ( !is_array( $GLOBALS[$name] ) ) {
751 throw new MWException( "MW global $name is not an array." );
752 }
753
754 // NOTE: do not use array_merge, it screws up for numeric keys.
755 $merged = $GLOBALS[$name];
756 foreach ( $values as $k => $v ) {
757 $merged[$k] = $v;
758 }
759 }
760
761 $this->setMwGlobals( $name, $merged );
762 }
763
764 /**
765 * Stashes the global instance of MediaWikiServices, and installs a new one,
766 * allowing test cases to override settings and services.
767 * The previous instance of MediaWikiServices will be restored on tearDown.
768 *
769 * @since 1.27
770 *
771 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
772 * @param callable[] $services An associative array of services to re-define. Keys are service
773 * names, values are callables.
774 *
775 * @return MediaWikiServices
776 * @throws MWException
777 */
778 protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
779 if ( !$configOverrides ) {
780 $configOverrides = new HashConfig();
781 }
782
783 $oldInstance = MediaWikiServices::getInstance();
784 $oldConfigFactory = $oldInstance->getConfigFactory();
785
786 $testConfig = self::makeTestConfig( null, $configOverrides );
787 $newInstance = new MediaWikiServices( $testConfig );
788
789 // Load the default wiring from the specified files.
790 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
791 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
792 $newInstance->loadWiringFiles( $wiringFiles );
793
794 // Provide a traditional hook point to allow extensions to configure services.
795 Hooks::run( 'MediaWikiServices', [ $newInstance ] );
796
797 foreach ( $services as $name => $callback ) {
798 $newInstance->redefineService( $name, $callback );
799 }
800
801 self::installTestServices(
802 $oldConfigFactory,
803 $newInstance
804 );
805 MediaWikiServices::forceGlobalInstance( $newInstance );
806
807 return $newInstance;
808 }
809
810 /**
811 * @since 1.27
812 * @param string|Language $lang
813 */
814 public function setUserLang( $lang ) {
815 RequestContext::getMain()->setLanguage( $lang );
816 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
817 }
818
819 /**
820 * @since 1.27
821 * @param string|Language $lang
822 */
823 public function setContentLang( $lang ) {
824 if ( $lang instanceof Language ) {
825 $langCode = $lang->getCode();
826 $langObj = $lang;
827 } else {
828 $langCode = $lang;
829 $langObj = Language::factory( $langCode );
830 }
831 $this->setMwGlobals( [
832 'wgLanguageCode' => $langCode,
833 'wgContLang' => $langObj,
834 ] );
835 }
836
837 /**
838 * Sets the logger for a specified channel, for the duration of the test.
839 * @since 1.27
840 * @param string $channel
841 * @param LoggerInterface $logger
842 */
843 protected function setLogger( $channel, LoggerInterface $logger ) {
844 // TODO: Once loggers are managed by MediaWikiServices, use
845 // overrideMwServices() to set loggers.
846
847 $provider = LoggerFactory::getProvider();
848 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
849 $singletons = $wrappedProvider->singletons;
850 if ( $provider instanceof MonologSpi ) {
851 if ( !isset( $this->loggers[$channel] ) ) {
852 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
853 ? $singletons['loggers'][$channel] : null;
854 }
855 $singletons['loggers'][$channel] = $logger;
856 } elseif ( $provider instanceof LegacySpi ) {
857 if ( !isset( $this->loggers[$channel] ) ) {
858 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
859 }
860 $singletons[$channel] = $logger;
861 } else {
862 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
863 . ' is not implemented' );
864 }
865 $wrappedProvider->singletons = $singletons;
866 }
867
868 /**
869 * Restores loggers replaced by setLogger().
870 * @since 1.27
871 */
872 private function restoreLoggers() {
873 $provider = LoggerFactory::getProvider();
874 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
875 $singletons = $wrappedProvider->singletons;
876 foreach ( $this->loggers as $channel => $logger ) {
877 if ( $provider instanceof MonologSpi ) {
878 if ( $logger === null ) {
879 unset( $singletons['loggers'][$channel] );
880 } else {
881 $singletons['loggers'][$channel] = $logger;
882 }
883 } elseif ( $provider instanceof LegacySpi ) {
884 if ( $logger === null ) {
885 unset( $singletons[$channel] );
886 } else {
887 $singletons[$channel] = $logger;
888 }
889 }
890 }
891 $wrappedProvider->singletons = $singletons;
892 $this->loggers = [];
893 }
894
895 /**
896 * @return string
897 * @since 1.18
898 */
899 public function dbPrefix() {
900 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
901 }
902
903 /**
904 * @return bool
905 * @since 1.18
906 */
907 public function needsDB() {
908 # if the test says it uses database tables, it needs the database
909 if ( $this->tablesUsed ) {
910 return true;
911 }
912
913 # if the test says it belongs to the Database group, it needs the database
914 $rc = new ReflectionClass( $this );
915 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
916 return true;
917 }
918
919 return false;
920 }
921
922 /**
923 * Insert a new page.
924 *
925 * Should be called from addDBData().
926 *
927 * @since 1.25 ($namespace in 1.28)
928 * @param string|title $pageName Page name or title
929 * @param string $text Page's content
930 * @param int $namespace Namespace id (name cannot already contain namespace)
931 * @return array Title object and page id
932 */
933 protected function insertPage(
934 $pageName,
935 $text = 'Sample page for unit test.',
936 $namespace = null
937 ) {
938 if ( is_string( $pageName ) ) {
939 $title = Title::newFromText( $pageName, $namespace );
940 } else {
941 $title = $pageName;
942 }
943
944 $user = static::getTestSysop()->getUser();
945 $comment = __METHOD__ . ': Sample page for unit test.';
946
947 // Avoid memory leak...?
948 // LinkCache::singleton()->clear();
949 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
950
951 $page = WikiPage::factory( $title );
952 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
953
954 return [
955 'title' => $title,
956 'id' => $page->getId(),
957 ];
958 }
959
960 /**
961 * Stub. If a test suite needs to add additional data to the database, it should
962 * implement this method and do so. This method is called once per test suite
963 * (i.e. once per class).
964 *
965 * Note data added by this method may be removed by resetDB() depending on
966 * the contents of $tablesUsed.
967 *
968 * To add additional data between test function runs, override prepareDB().
969 *
970 * @see addDBData()
971 * @see resetDB()
972 *
973 * @since 1.27
974 */
975 public function addDBDataOnce() {
976 }
977
978 /**
979 * Stub. Subclasses may override this to prepare the database.
980 * Called before every test run (test function or data set).
981 *
982 * @see addDBDataOnce()
983 * @see resetDB()
984 *
985 * @since 1.18
986 */
987 public function addDBData() {
988 }
989
990 private function addCoreDBData() {
991 if ( $this->db->getType() == 'oracle' ) {
992
993 # Insert 0 user to prevent FK violations
994 # Anonymous user
995 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
996 $this->db->insert( 'user', [
997 'user_id' => 0,
998 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
999 }
1000
1001 # Insert 0 page to prevent FK violations
1002 # Blank page
1003 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1004 $this->db->insert( 'page', [
1005 'page_id' => 0,
1006 'page_namespace' => 0,
1007 'page_title' => ' ',
1008 'page_restrictions' => null,
1009 'page_is_redirect' => 0,
1010 'page_is_new' => 0,
1011 'page_random' => 0,
1012 'page_touched' => $this->db->timestamp(),
1013 'page_latest' => 0,
1014 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1015 }
1016 }
1017
1018 User::resetIdByNameCache();
1019
1020 // Make sysop user
1021 $user = static::getTestSysop()->getUser();
1022
1023 // Make 1 page with 1 revision
1024 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1025 if ( $page->getId() == 0 ) {
1026 $page->doEditContent(
1027 new WikitextContent( 'UTContent' ),
1028 'UTPageSummary',
1029 EDIT_NEW,
1030 false,
1031 $user
1032 );
1033
1034 // doEditContent() probably started the session via
1035 // User::loadFromSession(). Close it now.
1036 if ( session_id() !== '' ) {
1037 session_write_close();
1038 session_id( '' );
1039 }
1040 }
1041 }
1042
1043 /**
1044 * Restores MediaWiki to using the table set (table prefix) it was using before
1045 * setupTestDB() was called. Useful if we need to perform database operations
1046 * after the test run has finished (such as saving logs or profiling info).
1047 *
1048 * @since 1.21
1049 */
1050 public static function teardownTestDB() {
1051 global $wgJobClasses;
1052
1053 if ( !self::$dbSetup ) {
1054 return;
1055 }
1056
1057 foreach ( $wgJobClasses as $type => $class ) {
1058 // Delete any jobs under the clone DB (or old prefix in other stores)
1059 JobQueueGroup::singleton()->get( $type )->delete();
1060 }
1061
1062 CloneDatabase::changePrefix( self::$oldTablePrefix );
1063
1064 self::$oldTablePrefix = false;
1065 self::$dbSetup = false;
1066 }
1067
1068 /**
1069 * Setups a database with the given prefix.
1070 *
1071 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1072 * Otherwise, it will clone the tables and change the prefix.
1073 *
1074 * Clones all tables in the given database (whatever database that connection has
1075 * open), to versions with the test prefix.
1076 *
1077 * @param Database $db Database to use
1078 * @param string $prefix Prefix to use for test tables
1079 * @return bool True if tables were cloned, false if only the prefix was changed
1080 */
1081 protected static function setupDatabaseWithTestPrefix( Database $db, $prefix ) {
1082 $tablesCloned = self::listTables( $db );
1083 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1084 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1085
1086 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1087 CloneDatabase::changePrefix( $prefix );
1088
1089 return false;
1090 } else {
1091 $dbClone->cloneTableStructure();
1092 return true;
1093 }
1094 }
1095
1096 /**
1097 * Set up all test DBs
1098 */
1099 public function setupAllTestDBs() {
1100 global $wgDBprefix;
1101
1102 self::$oldTablePrefix = $wgDBprefix;
1103
1104 $testPrefix = $this->dbPrefix();
1105
1106 // switch to a temporary clone of the database
1107 self::setupTestDB( $this->db, $testPrefix );
1108
1109 if ( self::isUsingExternalStoreDB() ) {
1110 self::setupExternalStoreTestDBs( $testPrefix );
1111 }
1112 }
1113
1114 /**
1115 * Creates an empty skeleton of the wiki database by cloning its structure
1116 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1117 * use the new set of tables (aka schema) instead of the original set.
1118 *
1119 * This is used to generate a dummy table set, typically consisting of temporary
1120 * tables, that will be used by tests instead of the original wiki database tables.
1121 *
1122 * @since 1.21
1123 *
1124 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1125 * by teardownTestDB() to return the wiki to using the original table set.
1126 *
1127 * @note this method only works when first called. Subsequent calls have no effect,
1128 * even if using different parameters.
1129 *
1130 * @param Database $db The database connection
1131 * @param string $prefix The prefix to use for the new table set (aka schema).
1132 *
1133 * @throws MWException If the database table prefix is already $prefix
1134 */
1135 public static function setupTestDB( Database $db, $prefix ) {
1136 if ( self::$dbSetup ) {
1137 return;
1138 }
1139
1140 if ( $db->tablePrefix() === $prefix ) {
1141 throw new MWException(
1142 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1143 }
1144
1145 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1146 // and Database no longer use global state.
1147
1148 self::$dbSetup = true;
1149
1150 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1151 return;
1152 }
1153
1154 // Assuming this isn't needed for External Store database, and not sure if the procedure
1155 // would be available there.
1156 if ( $db->getType() == 'oracle' ) {
1157 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1158 }
1159 }
1160
1161 /**
1162 * Clones the External Store database(s) for testing
1163 *
1164 * @param string $testPrefix Prefix for test tables
1165 */
1166 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1167 $connections = self::getExternalStoreDatabaseConnections();
1168 foreach ( $connections as $dbw ) {
1169 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1170 // prefix,. Even though listTables now uses tablePrefix, that
1171 // itself is populated from $wgDBprefix by default.
1172
1173 // We have to set it back, or we won't find the original 'blobs'
1174 // table to copy.
1175
1176 $dbw->tablePrefix( self::$oldTablePrefix );
1177 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1178 }
1179 }
1180
1181 /**
1182 * Gets master database connections for all of the ExternalStoreDB
1183 * stores configured in $wgDefaultExternalStore.
1184 *
1185 * @return Database[] Array of Database master connections
1186 */
1187
1188 protected static function getExternalStoreDatabaseConnections() {
1189 global $wgDefaultExternalStore;
1190
1191 /** @var ExternalStoreDB $externalStoreDB */
1192 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1193 $defaultArray = (array)$wgDefaultExternalStore;
1194 $dbws = [];
1195 foreach ( $defaultArray as $url ) {
1196 if ( strpos( $url, 'DB://' ) === 0 ) {
1197 list( $proto, $cluster ) = explode( '://', $url, 2 );
1198 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1199 // requires Database instead of plain DBConnRef/IDatabase
1200 $lb = $externalStoreDB->getLoadBalancer( $cluster );
1201 $dbw = $lb->getConnection( DB_MASTER );
1202 $dbws[] = $dbw;
1203 }
1204 }
1205
1206 return $dbws;
1207 }
1208
1209 /**
1210 * Check whether ExternalStoreDB is being used
1211 *
1212 * @return bool True if it's being used
1213 */
1214 protected static function isUsingExternalStoreDB() {
1215 global $wgDefaultExternalStore;
1216 if ( !$wgDefaultExternalStore ) {
1217 return false;
1218 }
1219
1220 $defaultArray = (array)$wgDefaultExternalStore;
1221 foreach ( $defaultArray as $url ) {
1222 if ( strpos( $url, 'DB://' ) === 0 ) {
1223 return true;
1224 }
1225 }
1226
1227 return false;
1228 }
1229
1230 /**
1231 * Empty all tables so they can be repopulated for tests
1232 *
1233 * @param Database $db|null Database to reset
1234 * @param array $tablesUsed Tables to reset
1235 */
1236 private function resetDB( $db, $tablesUsed ) {
1237 if ( $db ) {
1238 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1239 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1240
1241 // If any of the user tables were marked as used, we should clear all of them.
1242 if ( array_intersect( $tablesUsed, $userTables ) ) {
1243 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1244 TestUserRegistry::clear();
1245 }
1246
1247 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1248 foreach ( $tablesUsed as $tbl ) {
1249 // TODO: reset interwiki table to its original content.
1250 if ( $tbl == 'interwiki' ) {
1251 continue;
1252 }
1253
1254 if ( $truncate ) {
1255 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1256 } else {
1257 $db->delete( $tbl, '*', __METHOD__ );
1258 }
1259
1260 if ( $tbl === 'page' ) {
1261 // Forget about the pages since they don't
1262 // exist in the DB.
1263 LinkCache::singleton()->clear();
1264 }
1265 }
1266
1267 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1268 // Re-add core DB data that was deleted
1269 $this->addCoreDBData();
1270 }
1271 }
1272 }
1273
1274 /**
1275 * @since 1.18
1276 *
1277 * @param string $func
1278 * @param array $args
1279 *
1280 * @return mixed
1281 * @throws MWException
1282 */
1283 public function __call( $func, $args ) {
1284 static $compatibility = [
1285 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1286 ];
1287
1288 if ( isset( $compatibility[$func] ) ) {
1289 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1290 } else {
1291 throw new MWException( "Called non-existent $func method on "
1292 . get_class( $this ) );
1293 }
1294 }
1295
1296 /**
1297 * Used as a compatibility method for phpunit < 3.7.32
1298 * @param string $value
1299 * @param string $msg
1300 */
1301 private function assertEmpty2( $value, $msg ) {
1302 $this->assertTrue( $value == '', $msg );
1303 }
1304
1305 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1306 $tableName = substr( $tableName, strlen( $prefix ) );
1307 }
1308
1309 private static function isNotUnittest( $table ) {
1310 return strpos( $table, 'unittest_' ) !== 0;
1311 }
1312
1313 /**
1314 * @since 1.18
1315 *
1316 * @param Database $db
1317 *
1318 * @return array
1319 */
1320 public static function listTables( Database $db ) {
1321 $prefix = $db->tablePrefix();
1322 $tables = $db->listTables( $prefix, __METHOD__ );
1323
1324 if ( $db->getType() === 'mysql' ) {
1325 static $viewListCache = null;
1326 if ( $viewListCache === null ) {
1327 $viewListCache = $db->listViews( null, __METHOD__ );
1328 }
1329 // T45571: cannot clone VIEWs under MySQL
1330 $tables = array_diff( $tables, $viewListCache );
1331 }
1332 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1333
1334 // Don't duplicate test tables from the previous fataled run
1335 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1336
1337 if ( $db->getType() == 'sqlite' ) {
1338 $tables = array_flip( $tables );
1339 // these are subtables of searchindex and don't need to be duped/dropped separately
1340 unset( $tables['searchindex_content'] );
1341 unset( $tables['searchindex_segdir'] );
1342 unset( $tables['searchindex_segments'] );
1343 $tables = array_flip( $tables );
1344 }
1345
1346 return $tables;
1347 }
1348
1349 /**
1350 * @throws MWException
1351 * @since 1.18
1352 */
1353 protected function checkDbIsSupported() {
1354 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1355 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1356 }
1357 }
1358
1359 /**
1360 * @since 1.18
1361 * @param string $offset
1362 * @return mixed
1363 */
1364 public function getCliArg( $offset ) {
1365 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1366 return PHPUnitMaintClass::$additionalOptions[$offset];
1367 }
1368 }
1369
1370 /**
1371 * @since 1.18
1372 * @param string $offset
1373 * @param mixed $value
1374 */
1375 public function setCliArg( $offset, $value ) {
1376 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1377 }
1378
1379 /**
1380 * Don't throw a warning if $function is deprecated and called later
1381 *
1382 * @since 1.19
1383 *
1384 * @param string $function
1385 */
1386 public function hideDeprecated( $function ) {
1387 MediaWiki\suppressWarnings();
1388 wfDeprecated( $function );
1389 MediaWiki\restoreWarnings();
1390 }
1391
1392 /**
1393 * Asserts that the given database query yields the rows given by $expectedRows.
1394 * The expected rows should be given as indexed (not associative) arrays, with
1395 * the values given in the order of the columns in the $fields parameter.
1396 * Note that the rows are sorted by the columns given in $fields.
1397 *
1398 * @since 1.20
1399 *
1400 * @param string|array $table The table(s) to query
1401 * @param string|array $fields The columns to include in the result (and to sort by)
1402 * @param string|array $condition "where" condition(s)
1403 * @param array $expectedRows An array of arrays giving the expected rows.
1404 *
1405 * @throws MWException If this test cases's needsDB() method doesn't return true.
1406 * Test cases can use "@group Database" to enable database test support,
1407 * or list the tables under testing in $this->tablesUsed, or override the
1408 * needsDB() method.
1409 */
1410 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1411 if ( !$this->needsDB() ) {
1412 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1413 ' method should return true. Use @group Database or $this->tablesUsed.' );
1414 }
1415
1416 $db = wfGetDB( DB_SLAVE );
1417
1418 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1419 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1420
1421 $i = 0;
1422
1423 foreach ( $expectedRows as $expected ) {
1424 $r = $res->fetchRow();
1425 self::stripStringKeys( $r );
1426
1427 $i += 1;
1428 $this->assertNotEmpty( $r, "row #$i missing" );
1429
1430 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1431 }
1432
1433 $r = $res->fetchRow();
1434 self::stripStringKeys( $r );
1435
1436 $this->assertFalse( $r, "found extra row (after #$i)" );
1437 }
1438
1439 /**
1440 * Utility method taking an array of elements and wrapping
1441 * each element in its own array. Useful for data providers
1442 * that only return a single argument.
1443 *
1444 * @since 1.20
1445 *
1446 * @param array $elements
1447 *
1448 * @return array
1449 */
1450 protected function arrayWrap( array $elements ) {
1451 return array_map(
1452 function ( $element ) {
1453 return [ $element ];
1454 },
1455 $elements
1456 );
1457 }
1458
1459 /**
1460 * Assert that two arrays are equal. By default this means that both arrays need to hold
1461 * the same set of values. Using additional arguments, order and associated key can also
1462 * be set as relevant.
1463 *
1464 * @since 1.20
1465 *
1466 * @param array $expected
1467 * @param array $actual
1468 * @param bool $ordered If the order of the values should match
1469 * @param bool $named If the keys should match
1470 */
1471 protected function assertArrayEquals( array $expected, array $actual,
1472 $ordered = false, $named = false
1473 ) {
1474 if ( !$ordered ) {
1475 $this->objectAssociativeSort( $expected );
1476 $this->objectAssociativeSort( $actual );
1477 }
1478
1479 if ( !$named ) {
1480 $expected = array_values( $expected );
1481 $actual = array_values( $actual );
1482 }
1483
1484 call_user_func_array(
1485 [ $this, 'assertEquals' ],
1486 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1487 );
1488 }
1489
1490 /**
1491 * Put each HTML element on its own line and then equals() the results
1492 *
1493 * Use for nicely formatting of PHPUnit diff output when comparing very
1494 * simple HTML
1495 *
1496 * @since 1.20
1497 *
1498 * @param string $expected HTML on oneline
1499 * @param string $actual HTML on oneline
1500 * @param string $msg Optional message
1501 */
1502 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1503 $expected = str_replace( '>', ">\n", $expected );
1504 $actual = str_replace( '>', ">\n", $actual );
1505
1506 $this->assertEquals( $expected, $actual, $msg );
1507 }
1508
1509 /**
1510 * Does an associative sort that works for objects.
1511 *
1512 * @since 1.20
1513 *
1514 * @param array $array
1515 */
1516 protected function objectAssociativeSort( array &$array ) {
1517 uasort(
1518 $array,
1519 function ( $a, $b ) {
1520 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1521 }
1522 );
1523 }
1524
1525 /**
1526 * Utility function for eliminating all string keys from an array.
1527 * Useful to turn a database result row as returned by fetchRow() into
1528 * a pure indexed array.
1529 *
1530 * @since 1.20
1531 *
1532 * @param mixed $r The array to remove string keys from.
1533 */
1534 protected static function stripStringKeys( &$r ) {
1535 if ( !is_array( $r ) ) {
1536 return;
1537 }
1538
1539 foreach ( $r as $k => $v ) {
1540 if ( is_string( $k ) ) {
1541 unset( $r[$k] );
1542 }
1543 }
1544 }
1545
1546 /**
1547 * Asserts that the provided variable is of the specified
1548 * internal type or equals the $value argument. This is useful
1549 * for testing return types of functions that return a certain
1550 * type or *value* when not set or on error.
1551 *
1552 * @since 1.20
1553 *
1554 * @param string $type
1555 * @param mixed $actual
1556 * @param mixed $value
1557 * @param string $message
1558 */
1559 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1560 if ( $actual === $value ) {
1561 $this->assertTrue( true, $message );
1562 } else {
1563 $this->assertType( $type, $actual, $message );
1564 }
1565 }
1566
1567 /**
1568 * Asserts the type of the provided value. This can be either
1569 * in internal type such as boolean or integer, or a class or
1570 * interface the value extends or implements.
1571 *
1572 * @since 1.20
1573 *
1574 * @param string $type
1575 * @param mixed $actual
1576 * @param string $message
1577 */
1578 protected function assertType( $type, $actual, $message = '' ) {
1579 if ( class_exists( $type ) || interface_exists( $type ) ) {
1580 $this->assertInstanceOf( $type, $actual, $message );
1581 } else {
1582 $this->assertInternalType( $type, $actual, $message );
1583 }
1584 }
1585
1586 /**
1587 * Returns true if the given namespace defaults to Wikitext
1588 * according to $wgNamespaceContentModels
1589 *
1590 * @param int $ns The namespace ID to check
1591 *
1592 * @return bool
1593 * @since 1.21
1594 */
1595 protected function isWikitextNS( $ns ) {
1596 global $wgNamespaceContentModels;
1597
1598 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1599 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1600 }
1601
1602 return true;
1603 }
1604
1605 /**
1606 * Returns the ID of a namespace that defaults to Wikitext.
1607 *
1608 * @throws MWException If there is none.
1609 * @return int The ID of the wikitext Namespace
1610 * @since 1.21
1611 */
1612 protected function getDefaultWikitextNS() {
1613 global $wgNamespaceContentModels;
1614
1615 static $wikitextNS = null; // this is not going to change
1616 if ( $wikitextNS !== null ) {
1617 return $wikitextNS;
1618 }
1619
1620 // quickly short out on most common case:
1621 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1622 return NS_MAIN;
1623 }
1624
1625 // NOTE: prefer content namespaces
1626 $namespaces = array_unique( array_merge(
1627 MWNamespace::getContentNamespaces(),
1628 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1629 MWNamespace::getValidNamespaces()
1630 ) );
1631
1632 $namespaces = array_diff( $namespaces, [
1633 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1634 ] );
1635
1636 $talk = array_filter( $namespaces, function ( $ns ) {
1637 return MWNamespace::isTalk( $ns );
1638 } );
1639
1640 // prefer non-talk pages
1641 $namespaces = array_diff( $namespaces, $talk );
1642 $namespaces = array_merge( $namespaces, $talk );
1643
1644 // check default content model of each namespace
1645 foreach ( $namespaces as $ns ) {
1646 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1647 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1648 ) {
1649
1650 $wikitextNS = $ns;
1651
1652 return $wikitextNS;
1653 }
1654 }
1655
1656 // give up
1657 // @todo Inside a test, we could skip the test as incomplete.
1658 // But frequently, this is used in fixture setup.
1659 throw new MWException( "No namespace defaults to wikitext!" );
1660 }
1661
1662 /**
1663 * Check, if $wgDiff3 is set and ready to merge
1664 * Will mark the calling test as skipped, if not ready
1665 *
1666 * @since 1.21
1667 */
1668 protected function markTestSkippedIfNoDiff3() {
1669 global $wgDiff3;
1670
1671 # This check may also protect against code injection in
1672 # case of broken installations.
1673 MediaWiki\suppressWarnings();
1674 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1675 MediaWiki\restoreWarnings();
1676
1677 if ( !$haveDiff3 ) {
1678 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1679 }
1680 }
1681
1682 /**
1683 * Check if $extName is a loaded PHP extension, will skip the
1684 * test whenever it is not loaded.
1685 *
1686 * @since 1.21
1687 * @param string $extName
1688 * @return bool
1689 */
1690 protected function checkPHPExtension( $extName ) {
1691 $loaded = extension_loaded( $extName );
1692 if ( !$loaded ) {
1693 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1694 }
1695
1696 return $loaded;
1697 }
1698
1699 /**
1700 * Asserts that the given string is a valid HTML snippet.
1701 * Wraps the given string in the required top level tags and
1702 * then calls assertValidHtmlDocument().
1703 * The snippet is expected to be HTML 5.
1704 *
1705 * @since 1.23
1706 *
1707 * @note Will mark the test as skipped if the "tidy" module is not installed.
1708 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1709 * when automatic tidying is disabled.
1710 *
1711 * @param string $html An HTML snippet (treated as the contents of the body tag).
1712 */
1713 protected function assertValidHtmlSnippet( $html ) {
1714 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1715 $this->assertValidHtmlDocument( $html );
1716 }
1717
1718 /**
1719 * Asserts that the given string is valid HTML document.
1720 *
1721 * @since 1.23
1722 *
1723 * @note Will mark the test as skipped if the "tidy" module is not installed.
1724 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1725 * when automatic tidying is disabled.
1726 *
1727 * @param string $html A complete HTML document
1728 */
1729 protected function assertValidHtmlDocument( $html ) {
1730 // Note: we only validate if the tidy PHP extension is available.
1731 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1732 // of tidy. In that case however, we can not reliably detect whether a failing validation
1733 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1734 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1735 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1736 $this->markTestSkipped( 'Tidy extension not installed' );
1737 }
1738
1739 $errorBuffer = '';
1740 MWTidy::checkErrors( $html, $errorBuffer );
1741 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1742
1743 // Filter Tidy warnings which aren't useful for us.
1744 // Tidy eg. often cries about parameters missing which have actually
1745 // been deprecated since HTML4, thus we should not care about them.
1746 $errors = preg_grep(
1747 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1748 $allErrors, PREG_GREP_INVERT
1749 );
1750
1751 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1752 }
1753
1754 /**
1755 * @param array $matcher
1756 * @param string $actual
1757 * @param bool $isHtml
1758 *
1759 * @return bool
1760 */
1761 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1762 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1763 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1764 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1765 }
1766
1767 /**
1768 * Note: we are overriding this method to remove the deprecated error
1769 * @see https://phabricator.wikimedia.org/T71505
1770 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1771 * @deprecated
1772 *
1773 * @param array $matcher
1774 * @param string $actual
1775 * @param string $message
1776 * @param bool $isHtml
1777 */
1778 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1779 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1780
1781 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1782 }
1783
1784 /**
1785 * @see MediaWikiTestCase::assertTag
1786 * @deprecated
1787 *
1788 * @param array $matcher
1789 * @param string $actual
1790 * @param string $message
1791 * @param bool $isHtml
1792 */
1793 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1794 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1795
1796 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1797 }
1798
1799 /**
1800 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1801 * @return string
1802 */
1803 public static function wfResetOutputBuffersBarrier( $buffer ) {
1804 return $buffer;
1805 }
1806
1807 /**
1808 * Create a temporary hook handler which will be reset by tearDown.
1809 * This replaces other handlers for the same hook.
1810 * @param string $hookName Hook name
1811 * @param mixed $handler Value suitable for a hook handler
1812 * @since 1.28
1813 */
1814 protected function setTemporaryHook( $hookName, $handler ) {
1815 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
1816 }
1817
1818 }