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