Merge "Uncache things in WatchedItemStore::updateNotificationTimestamp"
[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 Psr\Log\LoggerInterface;
6
7 /**
8 * @since 1.18
9 */
10 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
11 /**
12 * $called tracks whether the setUp and tearDown method has been called.
13 * class extending MediaWikiTestCase usually override setUp and tearDown
14 * but forget to call the parent.
15 *
16 * The array format takes a method name as key and anything as a value.
17 * By asserting the key exist, we know the child class has called the
18 * parent.
19 *
20 * This property must be private, we do not want child to override it,
21 * they should call the appropriate parent method instead.
22 */
23 private $called = [];
24
25 /**
26 * @var TestUser[]
27 * @since 1.20
28 */
29 public static $users;
30
31 /**
32 * Primary database
33 *
34 * @var DatabaseBase
35 * @since 1.18
36 */
37 protected $db;
38
39 /**
40 * @var array
41 * @since 1.19
42 */
43 protected $tablesUsed = []; // tables with data
44
45 private static $useTemporaryTables = true;
46 private static $reuseDB = false;
47 private static $dbSetup = false;
48 private static $oldTablePrefix = false;
49
50 /**
51 * Original value of PHP's error_reporting setting.
52 *
53 * @var int
54 */
55 private $phpErrorLevel;
56
57 /**
58 * Holds the paths of temporary files/directories created through getNewTempFile,
59 * and getNewTempDirectory
60 *
61 * @var array
62 */
63 private $tmpFiles = [];
64
65 /**
66 * Holds original values of MediaWiki configuration settings
67 * to be restored in tearDown().
68 * See also setMwGlobals().
69 * @var array
70 */
71 private $mwGlobals = [];
72
73 /**
74 * Holds original loggers which have been replaced by setLogger()
75 * @var LoggerInterface[]
76 */
77 private $loggers = [];
78
79 /**
80 * Table name prefixes. Oracle likes it shorter.
81 */
82 const DB_PREFIX = 'unittest_';
83 const ORA_DB_PREFIX = 'ut_';
84
85 /**
86 * @var array
87 * @since 1.18
88 */
89 protected $supportedDBs = [
90 'mysql',
91 'sqlite',
92 'postgres',
93 'oracle'
94 ];
95
96 public function __construct( $name = null, array $data = [], $dataName = '' ) {
97 parent::__construct( $name, $data, $dataName );
98
99 $this->backupGlobals = false;
100 $this->backupStaticAttributes = false;
101 }
102
103 public function __destruct() {
104 // Complain if self::setUp() was called, but not self::tearDown()
105 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
106 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
107 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
108 }
109 }
110
111 public function run( PHPUnit_Framework_TestResult $result = null ) {
112 /* Some functions require some kind of caching, and will end up using the db,
113 * which we can't allow, as that would open a new connection for mysql.
114 * Replace with a HashBag. They would not be going to persist anyway.
115 */
116 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
117
118 // Sandbox APC by replacing with in-process hash instead.
119 // Ensures values are removed between tests.
120 ObjectCache::$instances['apc'] =
121 ObjectCache::$instances['xcache'] =
122 ObjectCache::$instances['wincache'] = new HashBagOStuff;
123
124 $needsResetDB = false;
125
126 if ( $this->needsDB() ) {
127 // set up a DB connection for this test to use
128
129 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
130 self::$reuseDB = $this->getCliArg( 'reuse-db' );
131
132 $this->db = wfGetDB( DB_MASTER );
133
134 $this->checkDbIsSupported();
135
136 if ( !self::$dbSetup ) {
137 $this->setupAllTestDBs();
138 $this->addCoreDBData();
139
140 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
141 $this->resetDB( $this->db, $this->tablesUsed );
142 }
143 }
144
145 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
146 // is available in subclass's setUpBeforeClass() and setUp() methods.
147 // This would also remove the need for the HACK that is oncePerClass().
148 if ( $this->oncePerClass() ) {
149 $this->addDBDataOnce();
150 }
151
152 $this->addDBData();
153 $needsResetDB = true;
154 }
155
156 parent::run( $result );
157
158 if ( $needsResetDB ) {
159 $this->resetDB( $this->db, $this->tablesUsed );
160 }
161 }
162
163 /**
164 * @return boolean
165 */
166 private function oncePerClass() {
167 // Remember current test class in the database connection,
168 // so we know when we need to run addData.
169
170 $class = static::class;
171
172 $first = !isset( $this->db->_hasDataForTestClass )
173 || $this->db->_hasDataForTestClass !== $class;
174
175 $this->db->_hasDataForTestClass = $class;
176 return $first;
177 }
178
179 /**
180 * @since 1.21
181 *
182 * @return bool
183 */
184 public function usesTemporaryTables() {
185 return self::$useTemporaryTables;
186 }
187
188 /**
189 * Obtains a new temporary file name
190 *
191 * The obtained filename is enlisted to be removed upon tearDown
192 *
193 * @since 1.20
194 *
195 * @return string Absolute name of the temporary file
196 */
197 protected function getNewTempFile() {
198 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
199 $this->tmpFiles[] = $fileName;
200
201 return $fileName;
202 }
203
204 /**
205 * obtains a new temporary directory
206 *
207 * The obtained directory is enlisted to be removed (recursively with all its contained
208 * files) upon tearDown.
209 *
210 * @since 1.20
211 *
212 * @return string Absolute name of the temporary directory
213 */
214 protected function getNewTempDirectory() {
215 // Starting of with a temporary /file/.
216 $fileName = $this->getNewTempFile();
217
218 // Converting the temporary /file/ to a /directory/
219 // The following is not atomic, but at least we now have a single place,
220 // where temporary directory creation is bundled and can be improved
221 unlink( $fileName );
222 $this->assertTrue( wfMkdirParents( $fileName ) );
223
224 return $fileName;
225 }
226
227 protected function setUp() {
228 parent::setUp();
229 $this->called['setUp'] = true;
230
231 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
232
233 // Cleaning up temporary files
234 foreach ( $this->tmpFiles as $fileName ) {
235 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
236 unlink( $fileName );
237 } elseif ( is_dir( $fileName ) ) {
238 wfRecursiveRemoveDir( $fileName );
239 }
240 }
241
242 if ( $this->needsDB() && $this->db ) {
243 // Clean up open transactions
244 while ( $this->db->trxLevel() > 0 ) {
245 $this->db->rollback( __METHOD__, 'flush' );
246 }
247 }
248
249 DeferredUpdates::clearPendingUpdates();
250
251 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
252 }
253
254 protected function addTmpFiles( $files ) {
255 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
256 }
257
258 protected function tearDown() {
259 global $wgRequest;
260
261 $status = ob_get_status();
262 if ( isset( $status['name'] ) &&
263 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
264 ) {
265 ob_end_flush();
266 }
267
268 $this->called['tearDown'] = true;
269 // Cleaning up temporary files
270 foreach ( $this->tmpFiles as $fileName ) {
271 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
272 unlink( $fileName );
273 } elseif ( is_dir( $fileName ) ) {
274 wfRecursiveRemoveDir( $fileName );
275 }
276 }
277
278 if ( $this->needsDB() && $this->db ) {
279 // Clean up open transactions
280 while ( $this->db->trxLevel() > 0 ) {
281 $this->db->rollback( __METHOD__, 'flush' );
282 }
283 }
284
285 // Restore mw globals
286 foreach ( $this->mwGlobals as $key => $value ) {
287 $GLOBALS[$key] = $value;
288 }
289 $this->mwGlobals = [];
290 $this->restoreLoggers();
291 RequestContext::resetMain();
292 MediaHandler::resetCache();
293 if ( session_id() !== '' ) {
294 session_write_close();
295 session_id( '' );
296 }
297 $wgRequest = new FauxRequest();
298 MediaWiki\Session\SessionManager::resetCache();
299
300 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
301
302 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
303 ini_set( 'error_reporting', $this->phpErrorLevel );
304
305 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
306 $newHex = strtoupper( dechex( $phpErrorLevel ) );
307 $message = "PHP error_reporting setting was left dirty: "
308 . "was 0x$oldHex before test, 0x$newHex after test!";
309
310 $this->fail( $message );
311 }
312
313 parent::tearDown();
314 }
315
316 /**
317 * Make sure MediaWikiTestCase extending classes have called their
318 * parent setUp method
319 */
320 final public function testMediaWikiTestCaseParentSetupCalled() {
321 $this->assertArrayHasKey( 'setUp', $this->called,
322 static::class . '::setUp() must call parent::setUp()'
323 );
324 }
325
326 /**
327 * Sets a global, maintaining a stashed version of the previous global to be
328 * restored in tearDown
329 *
330 * The key is added to the array of globals that will be reset afterwards
331 * in the tearDown().
332 *
333 * @example
334 * <code>
335 * protected function setUp() {
336 * $this->setMwGlobals( 'wgRestrictStuff', true );
337 * }
338 *
339 * function testFoo() {}
340 *
341 * function testBar() {}
342 * $this->assertTrue( self::getX()->doStuff() );
343 *
344 * $this->setMwGlobals( 'wgRestrictStuff', false );
345 * $this->assertTrue( self::getX()->doStuff() );
346 * }
347 *
348 * function testQuux() {}
349 * </code>
350 *
351 * @param array|string $pairs Key to the global variable, or an array
352 * of key/value pairs.
353 * @param mixed $value Value to set the global to (ignored
354 * if an array is given as first argument).
355 *
356 * @since 1.21
357 */
358 protected function setMwGlobals( $pairs, $value = null ) {
359 if ( is_string( $pairs ) ) {
360 $pairs = [ $pairs => $value ];
361 }
362
363 $this->stashMwGlobals( array_keys( $pairs ) );
364
365 foreach ( $pairs as $key => $value ) {
366 $GLOBALS[$key] = $value;
367 }
368 }
369
370 /**
371 * Stashes the global, will be restored in tearDown()
372 *
373 * Individual test functions may override globals through the setMwGlobals() function
374 * or directly. When directly overriding globals their keys should first be passed to this
375 * method in setUp to avoid breaking global state for other tests
376 *
377 * That way all other tests are executed with the same settings (instead of using the
378 * unreliable local settings for most tests and fix it only for some tests).
379 *
380 * @param array|string $globalKeys Key to the global variable, or an array of keys.
381 *
382 * @throws Exception When trying to stash an unset global
383 * @since 1.23
384 */
385 protected function stashMwGlobals( $globalKeys ) {
386 if ( is_string( $globalKeys ) ) {
387 $globalKeys = [ $globalKeys ];
388 }
389
390 foreach ( $globalKeys as $globalKey ) {
391 // NOTE: make sure we only save the global once or a second call to
392 // setMwGlobals() on the same global would override the original
393 // value.
394 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
395 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
396 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
397 }
398 // NOTE: we serialize then unserialize the value in case it is an object
399 // this stops any objects being passed by reference. We could use clone
400 // and if is_object but this does account for objects within objects!
401 try {
402 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
403 }
404 // NOTE; some things such as Closures are not serializable
405 // in this case just set the value!
406 catch ( Exception $e ) {
407 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
408 }
409 }
410 }
411 }
412
413 /**
414 * Merges the given values into a MW global array variable.
415 * Useful for setting some entries in a configuration array, instead of
416 * setting the entire array.
417 *
418 * @param string $name The name of the global, as in wgFooBar
419 * @param array $values The array containing the entries to set in that global
420 *
421 * @throws MWException If the designated global is not an array.
422 *
423 * @since 1.21
424 */
425 protected function mergeMwGlobalArrayValue( $name, $values ) {
426 if ( !isset( $GLOBALS[$name] ) ) {
427 $merged = $values;
428 } else {
429 if ( !is_array( $GLOBALS[$name] ) ) {
430 throw new MWException( "MW global $name is not an array." );
431 }
432
433 // NOTE: do not use array_merge, it screws up for numeric keys.
434 $merged = $GLOBALS[$name];
435 foreach ( $values as $k => $v ) {
436 $merged[$k] = $v;
437 }
438 }
439
440 $this->setMwGlobals( $name, $merged );
441 }
442
443 /**
444 * @since 1.27
445 * @param string|Language $lang
446 */
447 public function setUserLang( $lang ) {
448 RequestContext::getMain()->setLanguage( $lang );
449 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
450 }
451
452 /**
453 * @since 1.27
454 * @param string|Language $lang
455 */
456 public function setContentLang( $lang ) {
457 if ( $lang instanceof Language ) {
458 $langCode = $lang->getCode();
459 $langObj = $lang;
460 } else {
461 $langCode = $lang;
462 $langObj = Language::factory( $langCode );
463 }
464 $this->setMwGlobals( [
465 'wgLanguageCode' => $langCode,
466 'wgContLang' => $langObj,
467 ] );
468 }
469
470 /**
471 * Sets the logger for a specified channel, for the duration of the test.
472 * @since 1.27
473 * @param string $channel
474 * @param LoggerInterface $logger
475 */
476 protected function setLogger( $channel, LoggerInterface $logger ) {
477 $provider = LoggerFactory::getProvider();
478 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
479 $singletons = $wrappedProvider->singletons;
480 if ( $provider instanceof MonologSpi ) {
481 if ( !isset( $this->loggers[$channel] ) ) {
482 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
483 ? $singletons['loggers'][$channel] : null;
484 }
485 $singletons['loggers'][$channel] = $logger;
486 } elseif ( $provider instanceof LegacySpi ) {
487 if ( !isset( $this->loggers[$channel] ) ) {
488 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
489 }
490 $singletons[$channel] = $logger;
491 } else {
492 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
493 . ' is not implemented' );
494 }
495 $wrappedProvider->singletons = $singletons;
496 }
497
498 /**
499 * Restores loggers replaced by setLogger().
500 * @since 1.27
501 */
502 private function restoreLoggers() {
503 $provider = LoggerFactory::getProvider();
504 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
505 $singletons = $wrappedProvider->singletons;
506 foreach ( $this->loggers as $channel => $logger ) {
507 if ( $provider instanceof MonologSpi ) {
508 if ( $logger === null ) {
509 unset( $singletons['loggers'][$channel] );
510 } else {
511 $singletons['loggers'][$channel] = $logger;
512 }
513 } elseif ( $provider instanceof LegacySpi ) {
514 if ( $logger === null ) {
515 unset( $singletons[$channel] );
516 } else {
517 $singletons[$channel] = $logger;
518 }
519 }
520 }
521 $wrappedProvider->singletons = $singletons;
522 $this->loggers = [];
523 }
524
525 /**
526 * @return string
527 * @since 1.18
528 */
529 public function dbPrefix() {
530 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
531 }
532
533 /**
534 * @return bool
535 * @since 1.18
536 */
537 public function needsDB() {
538 # if the test says it uses database tables, it needs the database
539 if ( $this->tablesUsed ) {
540 return true;
541 }
542
543 # if the test says it belongs to the Database group, it needs the database
544 $rc = new ReflectionClass( $this );
545 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
546 return true;
547 }
548
549 return false;
550 }
551
552 /**
553 * Insert a new page.
554 *
555 * Should be called from addDBData().
556 *
557 * @since 1.25
558 * @param string $pageName Page name
559 * @param string $text Page's content
560 * @return array Title object and page id
561 */
562 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
563 $title = Title::newFromText( $pageName, 0 );
564
565 $user = User::newFromName( 'UTSysop' );
566 $comment = __METHOD__ . ': Sample page for unit test.';
567
568 $page = WikiPage::factory( $title );
569 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
570
571 return [
572 'title' => $title,
573 'id' => $page->getId(),
574 ];
575 }
576
577 /**
578 * Stub. If a test suite needs to add additional data to the database, it should
579 * implement this method and do so. This method is called once per test suite
580 * (i.e. once per class).
581 *
582 * Note data added by this method may be removed by resetDB() depending on
583 * the contents of $tablesUsed.
584 *
585 * To add additional data between test function runs, override prepareDB().
586 *
587 * @see addDBData()
588 * @see resetDB()
589 *
590 * @since 1.27
591 */
592 public function addDBDataOnce() {
593 }
594
595 /**
596 * Stub. Subclasses may override this to prepare the database.
597 * Called before every test run (test function or data set).
598 *
599 * @see addDBDataOnce()
600 * @see resetDB()
601 *
602 * @since 1.18
603 */
604 public function addDBData() {
605 }
606
607 private function addCoreDBData() {
608 if ( $this->db->getType() == 'oracle' ) {
609
610 # Insert 0 user to prevent FK violations
611 # Anonymous user
612 $this->db->insert( 'user', [
613 'user_id' => 0,
614 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
615
616 # Insert 0 page to prevent FK violations
617 # Blank page
618 $this->db->insert( 'page', [
619 'page_id' => 0,
620 'page_namespace' => 0,
621 'page_title' => ' ',
622 'page_restrictions' => null,
623 'page_is_redirect' => 0,
624 'page_is_new' => 0,
625 'page_random' => 0,
626 'page_touched' => $this->db->timestamp(),
627 'page_latest' => 0,
628 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
629 }
630
631 User::resetIdByNameCache();
632
633 // Make sysop user
634 $user = User::newFromName( 'UTSysop' );
635
636 if ( $user->idForName() == 0 ) {
637 $user->addToDatabase();
638 TestUser::setPasswordForUser( $user, 'UTSysopPassword' );
639 }
640
641 // Always set groups, because $this->resetDB() wipes them out
642 $user->addGroup( 'sysop' );
643 $user->addGroup( 'bureaucrat' );
644
645 // Make 1 page with 1 revision
646 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
647 if ( $page->getId() == 0 ) {
648 $page->doEditContent(
649 new WikitextContent( 'UTContent' ),
650 'UTPageSummary',
651 EDIT_NEW,
652 false,
653 $user
654 );
655
656 // doEditContent() probably started the session via
657 // User::loadFromSession(). Close it now.
658 if ( session_id() !== '' ) {
659 session_write_close();
660 session_id( '' );
661 }
662 }
663 }
664
665 /**
666 * Restores MediaWiki to using the table set (table prefix) it was using before
667 * setupTestDB() was called. Useful if we need to perform database operations
668 * after the test run has finished (such as saving logs or profiling info).
669 *
670 * @since 1.21
671 */
672 public static function teardownTestDB() {
673 global $wgJobClasses;
674
675 if ( !self::$dbSetup ) {
676 return;
677 }
678
679 foreach ( $wgJobClasses as $type => $class ) {
680 // Delete any jobs under the clone DB (or old prefix in other stores)
681 JobQueueGroup::singleton()->get( $type )->delete();
682 }
683
684 CloneDatabase::changePrefix( self::$oldTablePrefix );
685
686 self::$oldTablePrefix = false;
687 self::$dbSetup = false;
688 }
689
690 /**
691 * Setups a database with the given prefix.
692 *
693 * If reuseDB is true and certain conditions apply, it will just change the prefix.
694 * Otherwise, it will clone the tables and change the prefix.
695 *
696 * Clones all tables in the given database (whatever database that connection has
697 * open), to versions with the test prefix.
698 *
699 * @param DatabaseBase $db Database to use
700 * @param string $prefix Prefix to use for test tables
701 * @return bool True if tables were cloned, false if only the prefix was changed
702 */
703 protected static function setupDatabaseWithTestPrefix( DatabaseBase $db, $prefix ) {
704 $tablesCloned = self::listTables( $db );
705 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
706 $dbClone->useTemporaryTables( self::$useTemporaryTables );
707
708 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
709 CloneDatabase::changePrefix( $prefix );
710
711 return false;
712 } else {
713 $dbClone->cloneTableStructure();
714 return true;
715 }
716 }
717
718 /**
719 * Set up all test DBs
720 */
721 public function setupAllTestDBs() {
722 global $wgDBprefix;
723
724 self::$oldTablePrefix = $wgDBprefix;
725
726 $testPrefix = $this->dbPrefix();
727
728 // switch to a temporary clone of the database
729 self::setupTestDB( $this->db, $testPrefix );
730
731 if ( self::isUsingExternalStoreDB() ) {
732 self::setupExternalStoreTestDBs( $testPrefix );
733 }
734 }
735
736 /**
737 * Creates an empty skeleton of the wiki database by cloning its structure
738 * to equivalent tables using the given $prefix. Then sets MediaWiki to
739 * use the new set of tables (aka schema) instead of the original set.
740 *
741 * This is used to generate a dummy table set, typically consisting of temporary
742 * tables, that will be used by tests instead of the original wiki database tables.
743 *
744 * @since 1.21
745 *
746 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
747 * by teardownTestDB() to return the wiki to using the original table set.
748 *
749 * @note this method only works when first called. Subsequent calls have no effect,
750 * even if using different parameters.
751 *
752 * @param DatabaseBase $db The database connection
753 * @param string $prefix The prefix to use for the new table set (aka schema).
754 *
755 * @throws MWException If the database table prefix is already $prefix
756 */
757 public static function setupTestDB( DatabaseBase $db, $prefix ) {
758 if ( $db->tablePrefix() === $prefix ) {
759 throw new MWException(
760 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
761 }
762
763 if ( self::$dbSetup ) {
764 return;
765 }
766
767 self::$dbSetup = true;
768
769 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
770 return;
771 }
772
773 // Assuming this isn't needed for External Store database, and not sure if the procedure
774 // would be available there.
775 if ( $db->getType() == 'oracle' ) {
776 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
777 }
778 }
779
780 /**
781 * Clones the External Store database(s) for testing
782 *
783 * @param string $testPrefix Prefix for test tables
784 */
785 protected static function setupExternalStoreTestDBs( $testPrefix ) {
786 $connections = self::getExternalStoreDatabaseConnections();
787 foreach ( $connections as $dbw ) {
788 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
789 // prefix,. Even though listTables now uses tablePrefix, that
790 // itself is populated from $wgDBprefix by default.
791
792 // We have to set it back, or we won't find the original 'blobs'
793 // table to copy.
794
795 $dbw->tablePrefix( self::$oldTablePrefix );
796 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
797 }
798 }
799
800 /**
801 * Gets master database connections for all of the ExternalStoreDB
802 * stores configured in $wgDefaultExternalStore.
803 *
804 * @return array Array of DatabaseBase master connections
805 */
806
807 protected static function getExternalStoreDatabaseConnections() {
808 global $wgDefaultExternalStore;
809
810 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
811 $defaultArray = (array) $wgDefaultExternalStore;
812 $dbws = [];
813 foreach ( $defaultArray as $url ) {
814 if ( strpos( $url, 'DB://' ) === 0 ) {
815 list( $proto, $cluster ) = explode( '://', $url, 2 );
816 $dbw = $externalStoreDB->getMaster( $cluster );
817 $dbws[] = $dbw;
818 }
819 }
820
821 return $dbws;
822 }
823
824 /**
825 * Check whether ExternalStoreDB is being used
826 *
827 * @return bool True if it's being used
828 */
829 protected static function isUsingExternalStoreDB() {
830 global $wgDefaultExternalStore;
831 if ( !$wgDefaultExternalStore ) {
832 return false;
833 }
834
835 $defaultArray = (array) $wgDefaultExternalStore;
836 foreach ( $defaultArray as $url ) {
837 if ( strpos( $url, 'DB://' ) === 0 ) {
838 return true;
839 }
840 }
841
842 return false;
843 }
844
845 /**
846 * Empty all tables so they can be repopulated for tests
847 *
848 * @param DatabaseBase $db|null Database to reset
849 * @param array $tablesUsed Tables to reset
850 */
851 private function resetDB( $db, $tablesUsed ) {
852 if ( $db ) {
853 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
854 foreach ( $tablesUsed as $tbl ) {
855 // TODO: reset interwiki and user tables to their original content.
856 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
857 continue;
858 }
859
860 if ( $truncate ) {
861 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
862 } else {
863
864 $db->delete( $tbl, '*', __METHOD__ );
865 }
866
867 if ( $tbl === 'page' ) {
868 // Forget about the pages since they don't
869 // exist in the DB.
870 LinkCache::singleton()->clear();
871 }
872 }
873 }
874 }
875
876 /**
877 * @since 1.18
878 *
879 * @param string $func
880 * @param array $args
881 *
882 * @return mixed
883 * @throws MWException
884 */
885 public function __call( $func, $args ) {
886 static $compatibility = [
887 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
888 ];
889
890 if ( isset( $compatibility[$func] ) ) {
891 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
892 } else {
893 throw new MWException( "Called non-existent $func method on "
894 . get_class( $this ) );
895 }
896 }
897
898 /**
899 * Used as a compatibility method for phpunit < 3.7.32
900 * @param string $value
901 * @param string $msg
902 */
903 private function assertEmpty2( $value, $msg ) {
904 $this->assertTrue( $value == '', $msg );
905 }
906
907 private static function unprefixTable( &$tableName, $ind, $prefix ) {
908 $tableName = substr( $tableName, strlen( $prefix ) );
909 }
910
911 private static function isNotUnittest( $table ) {
912 return strpos( $table, 'unittest_' ) !== 0;
913 }
914
915 /**
916 * @since 1.18
917 *
918 * @param DatabaseBase $db
919 *
920 * @return array
921 */
922 public static function listTables( $db ) {
923 $prefix = $db->tablePrefix();
924 $tables = $db->listTables( $prefix, __METHOD__ );
925
926 if ( $db->getType() === 'mysql' ) {
927 # bug 43571: cannot clone VIEWs under MySQL
928 $views = $db->listViews( $prefix, __METHOD__ );
929 $tables = array_diff( $tables, $views );
930 }
931 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
932
933 // Don't duplicate test tables from the previous fataled run
934 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
935
936 if ( $db->getType() == 'sqlite' ) {
937 $tables = array_flip( $tables );
938 // these are subtables of searchindex and don't need to be duped/dropped separately
939 unset( $tables['searchindex_content'] );
940 unset( $tables['searchindex_segdir'] );
941 unset( $tables['searchindex_segments'] );
942 $tables = array_flip( $tables );
943 }
944
945 return $tables;
946 }
947
948 /**
949 * @throws MWException
950 * @since 1.18
951 */
952 protected function checkDbIsSupported() {
953 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
954 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
955 }
956 }
957
958 /**
959 * @since 1.18
960 * @param string $offset
961 * @return mixed
962 */
963 public function getCliArg( $offset ) {
964 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
965 return PHPUnitMaintClass::$additionalOptions[$offset];
966 }
967 }
968
969 /**
970 * @since 1.18
971 * @param string $offset
972 * @param mixed $value
973 */
974 public function setCliArg( $offset, $value ) {
975 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
976 }
977
978 /**
979 * Don't throw a warning if $function is deprecated and called later
980 *
981 * @since 1.19
982 *
983 * @param string $function
984 */
985 public function hideDeprecated( $function ) {
986 MediaWiki\suppressWarnings();
987 wfDeprecated( $function );
988 MediaWiki\restoreWarnings();
989 }
990
991 /**
992 * Asserts that the given database query yields the rows given by $expectedRows.
993 * The expected rows should be given as indexed (not associative) arrays, with
994 * the values given in the order of the columns in the $fields parameter.
995 * Note that the rows are sorted by the columns given in $fields.
996 *
997 * @since 1.20
998 *
999 * @param string|array $table The table(s) to query
1000 * @param string|array $fields The columns to include in the result (and to sort by)
1001 * @param string|array $condition "where" condition(s)
1002 * @param array $expectedRows An array of arrays giving the expected rows.
1003 *
1004 * @throws MWException If this test cases's needsDB() method doesn't return true.
1005 * Test cases can use "@group Database" to enable database test support,
1006 * or list the tables under testing in $this->tablesUsed, or override the
1007 * needsDB() method.
1008 */
1009 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1010 if ( !$this->needsDB() ) {
1011 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1012 ' method should return true. Use @group Database or $this->tablesUsed.' );
1013 }
1014
1015 $db = wfGetDB( DB_SLAVE );
1016
1017 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1018 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1019
1020 $i = 0;
1021
1022 foreach ( $expectedRows as $expected ) {
1023 $r = $res->fetchRow();
1024 self::stripStringKeys( $r );
1025
1026 $i += 1;
1027 $this->assertNotEmpty( $r, "row #$i missing" );
1028
1029 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1030 }
1031
1032 $r = $res->fetchRow();
1033 self::stripStringKeys( $r );
1034
1035 $this->assertFalse( $r, "found extra row (after #$i)" );
1036 }
1037
1038 /**
1039 * Utility method taking an array of elements and wrapping
1040 * each element in its own array. Useful for data providers
1041 * that only return a single argument.
1042 *
1043 * @since 1.20
1044 *
1045 * @param array $elements
1046 *
1047 * @return array
1048 */
1049 protected function arrayWrap( array $elements ) {
1050 return array_map(
1051 function ( $element ) {
1052 return [ $element ];
1053 },
1054 $elements
1055 );
1056 }
1057
1058 /**
1059 * Assert that two arrays are equal. By default this means that both arrays need to hold
1060 * the same set of values. Using additional arguments, order and associated key can also
1061 * be set as relevant.
1062 *
1063 * @since 1.20
1064 *
1065 * @param array $expected
1066 * @param array $actual
1067 * @param bool $ordered If the order of the values should match
1068 * @param bool $named If the keys should match
1069 */
1070 protected function assertArrayEquals( array $expected, array $actual,
1071 $ordered = false, $named = false
1072 ) {
1073 if ( !$ordered ) {
1074 $this->objectAssociativeSort( $expected );
1075 $this->objectAssociativeSort( $actual );
1076 }
1077
1078 if ( !$named ) {
1079 $expected = array_values( $expected );
1080 $actual = array_values( $actual );
1081 }
1082
1083 call_user_func_array(
1084 [ $this, 'assertEquals' ],
1085 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1086 );
1087 }
1088
1089 /**
1090 * Put each HTML element on its own line and then equals() the results
1091 *
1092 * Use for nicely formatting of PHPUnit diff output when comparing very
1093 * simple HTML
1094 *
1095 * @since 1.20
1096 *
1097 * @param string $expected HTML on oneline
1098 * @param string $actual HTML on oneline
1099 * @param string $msg Optional message
1100 */
1101 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1102 $expected = str_replace( '>', ">\n", $expected );
1103 $actual = str_replace( '>', ">\n", $actual );
1104
1105 $this->assertEquals( $expected, $actual, $msg );
1106 }
1107
1108 /**
1109 * Does an associative sort that works for objects.
1110 *
1111 * @since 1.20
1112 *
1113 * @param array $array
1114 */
1115 protected function objectAssociativeSort( array &$array ) {
1116 uasort(
1117 $array,
1118 function ( $a, $b ) {
1119 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1120 }
1121 );
1122 }
1123
1124 /**
1125 * Utility function for eliminating all string keys from an array.
1126 * Useful to turn a database result row as returned by fetchRow() into
1127 * a pure indexed array.
1128 *
1129 * @since 1.20
1130 *
1131 * @param mixed $r The array to remove string keys from.
1132 */
1133 protected static function stripStringKeys( &$r ) {
1134 if ( !is_array( $r ) ) {
1135 return;
1136 }
1137
1138 foreach ( $r as $k => $v ) {
1139 if ( is_string( $k ) ) {
1140 unset( $r[$k] );
1141 }
1142 }
1143 }
1144
1145 /**
1146 * Asserts that the provided variable is of the specified
1147 * internal type or equals the $value argument. This is useful
1148 * for testing return types of functions that return a certain
1149 * type or *value* when not set or on error.
1150 *
1151 * @since 1.20
1152 *
1153 * @param string $type
1154 * @param mixed $actual
1155 * @param mixed $value
1156 * @param string $message
1157 */
1158 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1159 if ( $actual === $value ) {
1160 $this->assertTrue( true, $message );
1161 } else {
1162 $this->assertType( $type, $actual, $message );
1163 }
1164 }
1165
1166 /**
1167 * Asserts the type of the provided value. This can be either
1168 * in internal type such as boolean or integer, or a class or
1169 * interface the value extends or implements.
1170 *
1171 * @since 1.20
1172 *
1173 * @param string $type
1174 * @param mixed $actual
1175 * @param string $message
1176 */
1177 protected function assertType( $type, $actual, $message = '' ) {
1178 if ( class_exists( $type ) || interface_exists( $type ) ) {
1179 $this->assertInstanceOf( $type, $actual, $message );
1180 } else {
1181 $this->assertInternalType( $type, $actual, $message );
1182 }
1183 }
1184
1185 /**
1186 * Returns true if the given namespace defaults to Wikitext
1187 * according to $wgNamespaceContentModels
1188 *
1189 * @param int $ns The namespace ID to check
1190 *
1191 * @return bool
1192 * @since 1.21
1193 */
1194 protected function isWikitextNS( $ns ) {
1195 global $wgNamespaceContentModels;
1196
1197 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1198 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1199 }
1200
1201 return true;
1202 }
1203
1204 /**
1205 * Returns the ID of a namespace that defaults to Wikitext.
1206 *
1207 * @throws MWException If there is none.
1208 * @return int The ID of the wikitext Namespace
1209 * @since 1.21
1210 */
1211 protected function getDefaultWikitextNS() {
1212 global $wgNamespaceContentModels;
1213
1214 static $wikitextNS = null; // this is not going to change
1215 if ( $wikitextNS !== null ) {
1216 return $wikitextNS;
1217 }
1218
1219 // quickly short out on most common case:
1220 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1221 return NS_MAIN;
1222 }
1223
1224 // NOTE: prefer content namespaces
1225 $namespaces = array_unique( array_merge(
1226 MWNamespace::getContentNamespaces(),
1227 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1228 MWNamespace::getValidNamespaces()
1229 ) );
1230
1231 $namespaces = array_diff( $namespaces, [
1232 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1233 ] );
1234
1235 $talk = array_filter( $namespaces, function ( $ns ) {
1236 return MWNamespace::isTalk( $ns );
1237 } );
1238
1239 // prefer non-talk pages
1240 $namespaces = array_diff( $namespaces, $talk );
1241 $namespaces = array_merge( $namespaces, $talk );
1242
1243 // check default content model of each namespace
1244 foreach ( $namespaces as $ns ) {
1245 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1246 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1247 ) {
1248
1249 $wikitextNS = $ns;
1250
1251 return $wikitextNS;
1252 }
1253 }
1254
1255 // give up
1256 // @todo Inside a test, we could skip the test as incomplete.
1257 // But frequently, this is used in fixture setup.
1258 throw new MWException( "No namespace defaults to wikitext!" );
1259 }
1260
1261 /**
1262 * Check, if $wgDiff3 is set and ready to merge
1263 * Will mark the calling test as skipped, if not ready
1264 *
1265 * @since 1.21
1266 */
1267 protected function markTestSkippedIfNoDiff3() {
1268 global $wgDiff3;
1269
1270 # This check may also protect against code injection in
1271 # case of broken installations.
1272 MediaWiki\suppressWarnings();
1273 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1274 MediaWiki\restoreWarnings();
1275
1276 if ( !$haveDiff3 ) {
1277 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1278 }
1279 }
1280
1281 /**
1282 * Check whether we have the 'gzip' commandline utility, will skip
1283 * the test whenever "gzip -V" fails.
1284 *
1285 * Result is cached at the process level.
1286 *
1287 * @return bool
1288 *
1289 * @since 1.21
1290 */
1291 protected function checkHasGzip() {
1292 static $haveGzip;
1293
1294 if ( $haveGzip === null ) {
1295 $retval = null;
1296 wfShellExec( 'gzip -V', $retval );
1297 $haveGzip = ( $retval === 0 );
1298 }
1299
1300 if ( !$haveGzip ) {
1301 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1302 }
1303
1304 return $haveGzip;
1305 }
1306
1307 /**
1308 * Check if $extName is a loaded PHP extension, will skip the
1309 * test whenever it is not loaded.
1310 *
1311 * @since 1.21
1312 * @param string $extName
1313 * @return bool
1314 */
1315 protected function checkPHPExtension( $extName ) {
1316 $loaded = extension_loaded( $extName );
1317 if ( !$loaded ) {
1318 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1319 }
1320
1321 return $loaded;
1322 }
1323
1324 /**
1325 * Asserts that an exception of the specified type occurs when running
1326 * the provided code.
1327 *
1328 * @since 1.21
1329 * @deprecated since 1.22 Use setExpectedException
1330 *
1331 * @param callable $code
1332 * @param string $expected
1333 * @param string $message
1334 */
1335 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1336 $pokemons = null;
1337
1338 try {
1339 call_user_func( $code );
1340 } catch ( Exception $pokemons ) {
1341 // Gotta Catch 'Em All!
1342 }
1343
1344 if ( $message === '' ) {
1345 $message = 'An exception of type "' . $expected . '" should have been thrown';
1346 }
1347
1348 $this->assertInstanceOf( $expected, $pokemons, $message );
1349 }
1350
1351 /**
1352 * Asserts that the given string is a valid HTML snippet.
1353 * Wraps the given string in the required top level tags and
1354 * then calls assertValidHtmlDocument().
1355 * The snippet is expected to be HTML 5.
1356 *
1357 * @since 1.23
1358 *
1359 * @note Will mark the test as skipped if the "tidy" module is not installed.
1360 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1361 * when automatic tidying is disabled.
1362 *
1363 * @param string $html An HTML snippet (treated as the contents of the body tag).
1364 */
1365 protected function assertValidHtmlSnippet( $html ) {
1366 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1367 $this->assertValidHtmlDocument( $html );
1368 }
1369
1370 /**
1371 * Asserts that the given string is valid HTML document.
1372 *
1373 * @since 1.23
1374 *
1375 * @note Will mark the test as skipped if the "tidy" module is not installed.
1376 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1377 * when automatic tidying is disabled.
1378 *
1379 * @param string $html A complete HTML document
1380 */
1381 protected function assertValidHtmlDocument( $html ) {
1382 // Note: we only validate if the tidy PHP extension is available.
1383 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1384 // of tidy. In that case however, we can not reliably detect whether a failing validation
1385 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1386 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1387 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1388 $this->markTestSkipped( 'Tidy extension not installed' );
1389 }
1390
1391 $errorBuffer = '';
1392 MWTidy::checkErrors( $html, $errorBuffer );
1393 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1394
1395 // Filter Tidy warnings which aren't useful for us.
1396 // Tidy eg. often cries about parameters missing which have actually
1397 // been deprecated since HTML4, thus we should not care about them.
1398 $errors = preg_grep(
1399 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1400 $allErrors, PREG_GREP_INVERT
1401 );
1402
1403 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1404 }
1405
1406 /**
1407 * @param array $matcher
1408 * @param string $actual
1409 * @param bool $isHtml
1410 *
1411 * @return bool
1412 */
1413 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1414 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1415 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1416 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1417 }
1418
1419 /**
1420 * Note: we are overriding this method to remove the deprecated error
1421 * @see https://phabricator.wikimedia.org/T71505
1422 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1423 * @deprecated
1424 *
1425 * @param array $matcher
1426 * @param string $actual
1427 * @param string $message
1428 * @param bool $isHtml
1429 */
1430 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1431 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1432
1433 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1434 }
1435
1436 /**
1437 * @see MediaWikiTestCase::assertTag
1438 * @deprecated
1439 *
1440 * @param array $matcher
1441 * @param string $actual
1442 * @param string $message
1443 * @param bool $isHtml
1444 */
1445 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1446 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1447
1448 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1449 }
1450
1451 /**
1452 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1453 * @return string
1454 */
1455 public static function wfResetOutputBuffersBarrier( $buffer ) {
1456 return $buffer;
1457 }
1458
1459 }