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