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