Merge "Improve HTMLSubmitField return value"
[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 $user->addGroup( 'sysop' );
641 $user->addGroup( 'bureaucrat' );
642 }
643
644 // Make 1 page with 1 revision
645 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
646 if ( $page->getId() == 0 ) {
647 $page->doEditContent(
648 new WikitextContent( 'UTContent' ),
649 'UTPageSummary',
650 EDIT_NEW,
651 false,
652 $user
653 );
654
655 // doEditContent() probably started the session via
656 // User::loadFromSession(). Close it now.
657 if ( session_id() !== '' ) {
658 session_write_close();
659 session_id( '' );
660 }
661 }
662 }
663
664 /**
665 * Restores MediaWiki to using the table set (table prefix) it was using before
666 * setupTestDB() was called. Useful if we need to perform database operations
667 * after the test run has finished (such as saving logs or profiling info).
668 *
669 * @since 1.21
670 */
671 public static function teardownTestDB() {
672 global $wgJobClasses;
673
674 if ( !self::$dbSetup ) {
675 return;
676 }
677
678 foreach ( $wgJobClasses as $type => $class ) {
679 // Delete any jobs under the clone DB (or old prefix in other stores)
680 JobQueueGroup::singleton()->get( $type )->delete();
681 }
682
683 CloneDatabase::changePrefix( self::$oldTablePrefix );
684
685 self::$oldTablePrefix = false;
686 self::$dbSetup = false;
687 }
688
689 /**
690 * Setups a database with the given prefix.
691 *
692 * If reuseDB is true and certain conditions apply, it will just change the prefix.
693 * Otherwise, it will clone the tables and change the prefix.
694 *
695 * Clones all tables in the given database (whatever database that connection has
696 * open), to versions with the test prefix.
697 *
698 * @param DatabaseBase $db Database to use
699 * @param string $prefix Prefix to use for test tables
700 * @return bool True if tables were cloned, false if only the prefix was changed
701 */
702 protected static function setupDatabaseWithTestPrefix( DatabaseBase $db, $prefix ) {
703 $tablesCloned = self::listTables( $db );
704 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
705 $dbClone->useTemporaryTables( self::$useTemporaryTables );
706
707 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
708 CloneDatabase::changePrefix( $prefix );
709
710 return false;
711 } else {
712 $dbClone->cloneTableStructure();
713 return true;
714 }
715 }
716
717 /**
718 * Set up all test DBs
719 */
720 public function setupAllTestDBs() {
721 global $wgDBprefix;
722
723 self::$oldTablePrefix = $wgDBprefix;
724
725 $testPrefix = $this->dbPrefix();
726
727 // switch to a temporary clone of the database
728 self::setupTestDB( $this->db, $testPrefix );
729
730 if ( self::isUsingExternalStoreDB() ) {
731 self::setupExternalStoreTestDBs( $testPrefix );
732 }
733 }
734
735 /**
736 * Creates an empty skeleton of the wiki database by cloning its structure
737 * to equivalent tables using the given $prefix. Then sets MediaWiki to
738 * use the new set of tables (aka schema) instead of the original set.
739 *
740 * This is used to generate a dummy table set, typically consisting of temporary
741 * tables, that will be used by tests instead of the original wiki database tables.
742 *
743 * @since 1.21
744 *
745 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
746 * by teardownTestDB() to return the wiki to using the original table set.
747 *
748 * @note this method only works when first called. Subsequent calls have no effect,
749 * even if using different parameters.
750 *
751 * @param DatabaseBase $db The database connection
752 * @param string $prefix The prefix to use for the new table set (aka schema).
753 *
754 * @throws MWException If the database table prefix is already $prefix
755 */
756 public static function setupTestDB( DatabaseBase $db, $prefix ) {
757 if ( $db->tablePrefix() === $prefix ) {
758 throw new MWException(
759 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
760 }
761
762 if ( self::$dbSetup ) {
763 return;
764 }
765
766 self::$dbSetup = true;
767
768 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
769 return;
770 }
771
772 // Assuming this isn't needed for External Store database, and not sure if the procedure
773 // would be available there.
774 if ( $db->getType() == 'oracle' ) {
775 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
776 }
777 }
778
779 /**
780 * Clones the External Store database(s) for testing
781 *
782 * @param string $testPrefix Prefix for test tables
783 */
784 protected static function setupExternalStoreTestDBs( $testPrefix ) {
785 $connections = self::getExternalStoreDatabaseConnections();
786 foreach ( $connections as $dbw ) {
787 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
788 // prefix,. Even though listTables now uses tablePrefix, that
789 // itself is populated from $wgDBprefix by default.
790
791 // We have to set it back, or we won't find the original 'blobs'
792 // table to copy.
793
794 $dbw->tablePrefix( self::$oldTablePrefix );
795 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
796 }
797 }
798
799 /**
800 * Gets master database connections for all of the ExternalStoreDB
801 * stores configured in $wgDefaultExternalStore.
802 *
803 * @return array Array of DatabaseBase master connections
804 */
805
806 protected static function getExternalStoreDatabaseConnections() {
807 global $wgDefaultExternalStore;
808
809 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
810 $defaultArray = (array) $wgDefaultExternalStore;
811 $dbws = [];
812 foreach ( $defaultArray as $url ) {
813 if ( strpos( $url, 'DB://' ) === 0 ) {
814 list( $proto, $cluster ) = explode( '://', $url, 2 );
815 $dbw = $externalStoreDB->getMaster( $cluster );
816 $dbws[] = $dbw;
817 }
818 }
819
820 return $dbws;
821 }
822
823 /**
824 * Check whether ExternalStoreDB is being used
825 *
826 * @return bool True if it's being used
827 */
828 protected static function isUsingExternalStoreDB() {
829 global $wgDefaultExternalStore;
830 if ( !$wgDefaultExternalStore ) {
831 return false;
832 }
833
834 $defaultArray = (array) $wgDefaultExternalStore;
835 foreach ( $defaultArray as $url ) {
836 if ( strpos( $url, 'DB://' ) === 0 ) {
837 return true;
838 }
839 }
840
841 return false;
842 }
843
844 /**
845 * Empty all tables so they can be repopulated for tests
846 *
847 * @param DatabaseBase $db|null Database to reset
848 * @param array $tablesUsed Tables to reset
849 */
850 private function resetDB( $db, $tablesUsed ) {
851 if ( $db ) {
852 $userTables = [ 'user', 'user_groups', 'user_properties' ];
853 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
854
855 // If any of the user tables were marked as used, we should clear all of them.
856 if ( array_intersect( $tablesUsed, $userTables ) ) {
857 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
858
859 // Totally clear User class in-process cache to avoid CAS errors
860 TestingAccessWrapper::newFromClass( 'User' )
861 ->getInProcessCache()
862 ->clear();
863 }
864
865 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
866 foreach ( $tablesUsed as $tbl ) {
867 // TODO: reset interwiki table to its original content.
868 if ( $tbl == 'interwiki' ) {
869 continue;
870 }
871
872 if ( $truncate ) {
873 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
874 } else {
875 $db->delete( $tbl, '*', __METHOD__ );
876 }
877
878 if ( $tbl === 'page' ) {
879 // Forget about the pages since they don't
880 // exist in the DB.
881 LinkCache::singleton()->clear();
882 }
883 }
884
885 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
886 // Re-add core DB data that was deleted
887 $this->addCoreDBData();
888 }
889 }
890 }
891
892 /**
893 * @since 1.18
894 *
895 * @param string $func
896 * @param array $args
897 *
898 * @return mixed
899 * @throws MWException
900 */
901 public function __call( $func, $args ) {
902 static $compatibility = [
903 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
904 ];
905
906 if ( isset( $compatibility[$func] ) ) {
907 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
908 } else {
909 throw new MWException( "Called non-existent $func method on "
910 . get_class( $this ) );
911 }
912 }
913
914 /**
915 * Used as a compatibility method for phpunit < 3.7.32
916 * @param string $value
917 * @param string $msg
918 */
919 private function assertEmpty2( $value, $msg ) {
920 $this->assertTrue( $value == '', $msg );
921 }
922
923 private static function unprefixTable( &$tableName, $ind, $prefix ) {
924 $tableName = substr( $tableName, strlen( $prefix ) );
925 }
926
927 private static function isNotUnittest( $table ) {
928 return strpos( $table, 'unittest_' ) !== 0;
929 }
930
931 /**
932 * @since 1.18
933 *
934 * @param DatabaseBase $db
935 *
936 * @return array
937 */
938 public static function listTables( $db ) {
939 $prefix = $db->tablePrefix();
940 $tables = $db->listTables( $prefix, __METHOD__ );
941
942 if ( $db->getType() === 'mysql' ) {
943 # bug 43571: cannot clone VIEWs under MySQL
944 $views = $db->listViews( $prefix, __METHOD__ );
945 $tables = array_diff( $tables, $views );
946 }
947 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
948
949 // Don't duplicate test tables from the previous fataled run
950 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
951
952 if ( $db->getType() == 'sqlite' ) {
953 $tables = array_flip( $tables );
954 // these are subtables of searchindex and don't need to be duped/dropped separately
955 unset( $tables['searchindex_content'] );
956 unset( $tables['searchindex_segdir'] );
957 unset( $tables['searchindex_segments'] );
958 $tables = array_flip( $tables );
959 }
960
961 return $tables;
962 }
963
964 /**
965 * @throws MWException
966 * @since 1.18
967 */
968 protected function checkDbIsSupported() {
969 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
970 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
971 }
972 }
973
974 /**
975 * @since 1.18
976 * @param string $offset
977 * @return mixed
978 */
979 public function getCliArg( $offset ) {
980 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
981 return PHPUnitMaintClass::$additionalOptions[$offset];
982 }
983 }
984
985 /**
986 * @since 1.18
987 * @param string $offset
988 * @param mixed $value
989 */
990 public function setCliArg( $offset, $value ) {
991 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
992 }
993
994 /**
995 * Don't throw a warning if $function is deprecated and called later
996 *
997 * @since 1.19
998 *
999 * @param string $function
1000 */
1001 public function hideDeprecated( $function ) {
1002 MediaWiki\suppressWarnings();
1003 wfDeprecated( $function );
1004 MediaWiki\restoreWarnings();
1005 }
1006
1007 /**
1008 * Asserts that the given database query yields the rows given by $expectedRows.
1009 * The expected rows should be given as indexed (not associative) arrays, with
1010 * the values given in the order of the columns in the $fields parameter.
1011 * Note that the rows are sorted by the columns given in $fields.
1012 *
1013 * @since 1.20
1014 *
1015 * @param string|array $table The table(s) to query
1016 * @param string|array $fields The columns to include in the result (and to sort by)
1017 * @param string|array $condition "where" condition(s)
1018 * @param array $expectedRows An array of arrays giving the expected rows.
1019 *
1020 * @throws MWException If this test cases's needsDB() method doesn't return true.
1021 * Test cases can use "@group Database" to enable database test support,
1022 * or list the tables under testing in $this->tablesUsed, or override the
1023 * needsDB() method.
1024 */
1025 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1026 if ( !$this->needsDB() ) {
1027 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1028 ' method should return true. Use @group Database or $this->tablesUsed.' );
1029 }
1030
1031 $db = wfGetDB( DB_SLAVE );
1032
1033 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1034 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1035
1036 $i = 0;
1037
1038 foreach ( $expectedRows as $expected ) {
1039 $r = $res->fetchRow();
1040 self::stripStringKeys( $r );
1041
1042 $i += 1;
1043 $this->assertNotEmpty( $r, "row #$i missing" );
1044
1045 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1046 }
1047
1048 $r = $res->fetchRow();
1049 self::stripStringKeys( $r );
1050
1051 $this->assertFalse( $r, "found extra row (after #$i)" );
1052 }
1053
1054 /**
1055 * Utility method taking an array of elements and wrapping
1056 * each element in its own array. Useful for data providers
1057 * that only return a single argument.
1058 *
1059 * @since 1.20
1060 *
1061 * @param array $elements
1062 *
1063 * @return array
1064 */
1065 protected function arrayWrap( array $elements ) {
1066 return array_map(
1067 function ( $element ) {
1068 return [ $element ];
1069 },
1070 $elements
1071 );
1072 }
1073
1074 /**
1075 * Assert that two arrays are equal. By default this means that both arrays need to hold
1076 * the same set of values. Using additional arguments, order and associated key can also
1077 * be set as relevant.
1078 *
1079 * @since 1.20
1080 *
1081 * @param array $expected
1082 * @param array $actual
1083 * @param bool $ordered If the order of the values should match
1084 * @param bool $named If the keys should match
1085 */
1086 protected function assertArrayEquals( array $expected, array $actual,
1087 $ordered = false, $named = false
1088 ) {
1089 if ( !$ordered ) {
1090 $this->objectAssociativeSort( $expected );
1091 $this->objectAssociativeSort( $actual );
1092 }
1093
1094 if ( !$named ) {
1095 $expected = array_values( $expected );
1096 $actual = array_values( $actual );
1097 }
1098
1099 call_user_func_array(
1100 [ $this, 'assertEquals' ],
1101 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1102 );
1103 }
1104
1105 /**
1106 * Put each HTML element on its own line and then equals() the results
1107 *
1108 * Use for nicely formatting of PHPUnit diff output when comparing very
1109 * simple HTML
1110 *
1111 * @since 1.20
1112 *
1113 * @param string $expected HTML on oneline
1114 * @param string $actual HTML on oneline
1115 * @param string $msg Optional message
1116 */
1117 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1118 $expected = str_replace( '>', ">\n", $expected );
1119 $actual = str_replace( '>', ">\n", $actual );
1120
1121 $this->assertEquals( $expected, $actual, $msg );
1122 }
1123
1124 /**
1125 * Does an associative sort that works for objects.
1126 *
1127 * @since 1.20
1128 *
1129 * @param array $array
1130 */
1131 protected function objectAssociativeSort( array &$array ) {
1132 uasort(
1133 $array,
1134 function ( $a, $b ) {
1135 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1136 }
1137 );
1138 }
1139
1140 /**
1141 * Utility function for eliminating all string keys from an array.
1142 * Useful to turn a database result row as returned by fetchRow() into
1143 * a pure indexed array.
1144 *
1145 * @since 1.20
1146 *
1147 * @param mixed $r The array to remove string keys from.
1148 */
1149 protected static function stripStringKeys( &$r ) {
1150 if ( !is_array( $r ) ) {
1151 return;
1152 }
1153
1154 foreach ( $r as $k => $v ) {
1155 if ( is_string( $k ) ) {
1156 unset( $r[$k] );
1157 }
1158 }
1159 }
1160
1161 /**
1162 * Asserts that the provided variable is of the specified
1163 * internal type or equals the $value argument. This is useful
1164 * for testing return types of functions that return a certain
1165 * type or *value* when not set or on error.
1166 *
1167 * @since 1.20
1168 *
1169 * @param string $type
1170 * @param mixed $actual
1171 * @param mixed $value
1172 * @param string $message
1173 */
1174 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1175 if ( $actual === $value ) {
1176 $this->assertTrue( true, $message );
1177 } else {
1178 $this->assertType( $type, $actual, $message );
1179 }
1180 }
1181
1182 /**
1183 * Asserts the type of the provided value. This can be either
1184 * in internal type such as boolean or integer, or a class or
1185 * interface the value extends or implements.
1186 *
1187 * @since 1.20
1188 *
1189 * @param string $type
1190 * @param mixed $actual
1191 * @param string $message
1192 */
1193 protected function assertType( $type, $actual, $message = '' ) {
1194 if ( class_exists( $type ) || interface_exists( $type ) ) {
1195 $this->assertInstanceOf( $type, $actual, $message );
1196 } else {
1197 $this->assertInternalType( $type, $actual, $message );
1198 }
1199 }
1200
1201 /**
1202 * Returns true if the given namespace defaults to Wikitext
1203 * according to $wgNamespaceContentModels
1204 *
1205 * @param int $ns The namespace ID to check
1206 *
1207 * @return bool
1208 * @since 1.21
1209 */
1210 protected function isWikitextNS( $ns ) {
1211 global $wgNamespaceContentModels;
1212
1213 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1214 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1215 }
1216
1217 return true;
1218 }
1219
1220 /**
1221 * Returns the ID of a namespace that defaults to Wikitext.
1222 *
1223 * @throws MWException If there is none.
1224 * @return int The ID of the wikitext Namespace
1225 * @since 1.21
1226 */
1227 protected function getDefaultWikitextNS() {
1228 global $wgNamespaceContentModels;
1229
1230 static $wikitextNS = null; // this is not going to change
1231 if ( $wikitextNS !== null ) {
1232 return $wikitextNS;
1233 }
1234
1235 // quickly short out on most common case:
1236 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1237 return NS_MAIN;
1238 }
1239
1240 // NOTE: prefer content namespaces
1241 $namespaces = array_unique( array_merge(
1242 MWNamespace::getContentNamespaces(),
1243 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1244 MWNamespace::getValidNamespaces()
1245 ) );
1246
1247 $namespaces = array_diff( $namespaces, [
1248 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1249 ] );
1250
1251 $talk = array_filter( $namespaces, function ( $ns ) {
1252 return MWNamespace::isTalk( $ns );
1253 } );
1254
1255 // prefer non-talk pages
1256 $namespaces = array_diff( $namespaces, $talk );
1257 $namespaces = array_merge( $namespaces, $talk );
1258
1259 // check default content model of each namespace
1260 foreach ( $namespaces as $ns ) {
1261 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1262 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1263 ) {
1264
1265 $wikitextNS = $ns;
1266
1267 return $wikitextNS;
1268 }
1269 }
1270
1271 // give up
1272 // @todo Inside a test, we could skip the test as incomplete.
1273 // But frequently, this is used in fixture setup.
1274 throw new MWException( "No namespace defaults to wikitext!" );
1275 }
1276
1277 /**
1278 * Check, if $wgDiff3 is set and ready to merge
1279 * Will mark the calling test as skipped, if not ready
1280 *
1281 * @since 1.21
1282 */
1283 protected function markTestSkippedIfNoDiff3() {
1284 global $wgDiff3;
1285
1286 # This check may also protect against code injection in
1287 # case of broken installations.
1288 MediaWiki\suppressWarnings();
1289 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1290 MediaWiki\restoreWarnings();
1291
1292 if ( !$haveDiff3 ) {
1293 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1294 }
1295 }
1296
1297 /**
1298 * Check whether we have the 'gzip' commandline utility, will skip
1299 * the test whenever "gzip -V" fails.
1300 *
1301 * Result is cached at the process level.
1302 *
1303 * @return bool
1304 *
1305 * @since 1.21
1306 */
1307 protected function checkHasGzip() {
1308 static $haveGzip;
1309
1310 if ( $haveGzip === null ) {
1311 $retval = null;
1312 wfShellExec( 'gzip -V', $retval );
1313 $haveGzip = ( $retval === 0 );
1314 }
1315
1316 if ( !$haveGzip ) {
1317 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1318 }
1319
1320 return $haveGzip;
1321 }
1322
1323 /**
1324 * Check if $extName is a loaded PHP extension, will skip the
1325 * test whenever it is not loaded.
1326 *
1327 * @since 1.21
1328 * @param string $extName
1329 * @return bool
1330 */
1331 protected function checkPHPExtension( $extName ) {
1332 $loaded = extension_loaded( $extName );
1333 if ( !$loaded ) {
1334 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1335 }
1336
1337 return $loaded;
1338 }
1339
1340 /**
1341 * Asserts that the given string is a valid HTML snippet.
1342 * Wraps the given string in the required top level tags and
1343 * then calls assertValidHtmlDocument().
1344 * The snippet is expected to be HTML 5.
1345 *
1346 * @since 1.23
1347 *
1348 * @note Will mark the test as skipped if the "tidy" module is not installed.
1349 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1350 * when automatic tidying is disabled.
1351 *
1352 * @param string $html An HTML snippet (treated as the contents of the body tag).
1353 */
1354 protected function assertValidHtmlSnippet( $html ) {
1355 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1356 $this->assertValidHtmlDocument( $html );
1357 }
1358
1359 /**
1360 * Asserts that the given string is valid HTML document.
1361 *
1362 * @since 1.23
1363 *
1364 * @note Will mark the test as skipped if the "tidy" module is not installed.
1365 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1366 * when automatic tidying is disabled.
1367 *
1368 * @param string $html A complete HTML document
1369 */
1370 protected function assertValidHtmlDocument( $html ) {
1371 // Note: we only validate if the tidy PHP extension is available.
1372 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1373 // of tidy. In that case however, we can not reliably detect whether a failing validation
1374 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1375 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1376 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1377 $this->markTestSkipped( 'Tidy extension not installed' );
1378 }
1379
1380 $errorBuffer = '';
1381 MWTidy::checkErrors( $html, $errorBuffer );
1382 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1383
1384 // Filter Tidy warnings which aren't useful for us.
1385 // Tidy eg. often cries about parameters missing which have actually
1386 // been deprecated since HTML4, thus we should not care about them.
1387 $errors = preg_grep(
1388 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1389 $allErrors, PREG_GREP_INVERT
1390 );
1391
1392 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1393 }
1394
1395 /**
1396 * @param array $matcher
1397 * @param string $actual
1398 * @param bool $isHtml
1399 *
1400 * @return bool
1401 */
1402 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1403 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1404 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1405 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1406 }
1407
1408 /**
1409 * Note: we are overriding this method to remove the deprecated error
1410 * @see https://phabricator.wikimedia.org/T71505
1411 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1412 * @deprecated
1413 *
1414 * @param array $matcher
1415 * @param string $actual
1416 * @param string $message
1417 * @param bool $isHtml
1418 */
1419 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1420 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1421
1422 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1423 }
1424
1425 /**
1426 * @see MediaWikiTestCase::assertTag
1427 * @deprecated
1428 *
1429 * @param array $matcher
1430 * @param string $actual
1431 * @param string $message
1432 * @param bool $isHtml
1433 */
1434 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1435 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1436
1437 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1438 }
1439
1440 /**
1441 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1442 * @return string
1443 */
1444 public static function wfResetOutputBuffersBarrier( $buffer ) {
1445 return $buffer;
1446 }
1447
1448 }