Merge "Add version number to deprecated setting"
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
4 public $suite;
5 public $regex = '';
6 public $runDisabled = false;
7
8 /**
9 * @var Array of TestUser
10 */
11 public static $users;
12
13 /**
14 * @var DatabaseBase
15 */
16 protected $db;
17 protected $oldTablePrefix;
18 protected $useTemporaryTables = true;
19 protected $reuseDB = false;
20 protected $tablesUsed = array(); // tables with data
21
22 private static $dbSetup = false;
23
24 /**
25 * Holds the paths of temporary files/directories created through getNewTempFile,
26 * and getNewTempDirectory
27 *
28 * @var array
29 */
30 private $tmpfiles = array();
31
32 /**
33 * Holds original values of MediaWiki configuration settings
34 * to be restored in tearDown().
35 * See also setMwGlobal().
36 * @var array
37 */
38 private $mwGlobals = array();
39
40 /**
41 * Table name prefixes. Oracle likes it shorter.
42 */
43 const DB_PREFIX = 'unittest_';
44 const ORA_DB_PREFIX = 'ut_';
45
46 protected $supportedDBs = array(
47 'mysql',
48 'sqlite',
49 'postgres',
50 'oracle'
51 );
52
53 function __construct( $name = null, array $data = array(), $dataName = '' ) {
54 parent::__construct( $name, $data, $dataName );
55
56 $this->backupGlobals = false;
57 $this->backupStaticAttributes = false;
58 }
59
60 function run( PHPUnit_Framework_TestResult $result = NULL ) {
61 /* Some functions require some kind of caching, and will end up using the db,
62 * which we can't allow, as that would open a new connection for mysql.
63 * Replace with a HashBag. They would not be going to persist anyway.
64 */
65 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
66
67 if( $this->needsDB() ) {
68 global $wgDBprefix;
69
70 $this->useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
71 $this->reuseDB = $this->getCliArg('reuse-db');
72
73 $this->db = wfGetDB( DB_MASTER );
74
75 $this->checkDbIsSupported();
76
77 $this->oldTablePrefix = $wgDBprefix;
78
79 if( !self::$dbSetup ) {
80 $this->initDB();
81 self::$dbSetup = true;
82 }
83
84 $this->addCoreDBData();
85 $this->addDBData();
86
87 parent::run( $result );
88
89 $this->resetDB();
90 } else {
91 parent::run( $result );
92 }
93 }
94
95 /**
96 * obtains a new temporary file name
97 *
98 * The obtained filename is enlisted to be removed upon tearDown
99 *
100 * @returns string: absolute name of the temporary file
101 */
102 protected function getNewTempFile() {
103 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
104 $this->tmpfiles[] = $fname;
105 return $fname;
106 }
107
108 /**
109 * obtains a new temporary directory
110 *
111 * The obtained directory is enlisted to be removed (recursively with all its contained
112 * files) upon tearDown.
113 *
114 * @returns string: absolute name of the temporary directory
115 */
116 protected function getNewTempDirectory() {
117 // Starting of with a temporary /file/.
118 $fname = $this->getNewTempFile();
119
120 // Converting the temporary /file/ to a /directory/
121 //
122 // The following is not atomic, but at least we now have a single place,
123 // where temporary directory creation is bundled and can be improved
124 unlink( $fname );
125 $this->assertTrue( wfMkdirParents( $fname ) );
126 return $fname;
127 }
128
129 /**
130 * setUp and tearDown should (where significant)
131 * happen in reverse order.
132 */
133 protected function setUp() {
134 parent::setUp();
135
136 // Cleaning up temporary files
137 foreach ( $this->tmpfiles as $fname ) {
138 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
139 unlink( $fname );
140 } elseif ( is_dir( $fname ) ) {
141 wfRecursiveRemoveDir( $fname );
142 }
143 }
144
145 // Clean up open transactions
146 if ( $this->needsDB() && $this->db ) {
147 while( $this->db->trxLevel() > 0 ) {
148 $this->db->rollback();
149 }
150 }
151 }
152
153 protected function tearDown() {
154 // Cleaning up temporary files
155 foreach ( $this->tmpfiles as $fname ) {
156 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
157 unlink( $fname );
158 } elseif ( is_dir( $fname ) ) {
159 wfRecursiveRemoveDir( $fname );
160 }
161 }
162
163 // Clean up open transactions
164 if ( $this->needsDB() && $this->db ) {
165 while( $this->db->trxLevel() > 0 ) {
166 $this->db->rollback();
167 }
168 }
169
170 // Restore mw globals
171 foreach ( $this->mwGlobals as $key => $value ) {
172 $GLOBALS[$key] = $value;
173 }
174 $this->mwGlobals = array();
175
176 parent::tearDown();
177 }
178
179 /**
180 * Individual test functions may override globals (either directly or through this
181 * setMwGlobals() function), however one must call this method at least once for
182 * each key within the setUp().
183 * That way the key is added to the array of globals that will be reset afterwards
184 * in the tearDown(). And, equally important, that way all other tests are executed
185 * with the same settings (instead of using the unreliable local settings for most
186 * tests and fix it only for some tests).
187 *
188 * @example
189 * <code>
190 * protected function setUp() {
191 * $this->setMwGlobals( 'wgRestrictStuff', true );
192 * }
193 *
194 * function testFoo() {}
195 *
196 * function testBar() {}
197 * $this->assertTrue( self::getX()->doStuff() );
198 *
199 * $this->setMwGlobals( 'wgRestrictStuff', false );
200 * $this->assertTrue( self::getX()->doStuff() );
201 * }
202 *
203 * function testQuux() {}
204 * </code>
205 *
206 * @param array|string $pairs Key to the global variable, or an array
207 * of key/value pairs.
208 * @param mixed $value Value to set the global to (ignored
209 * if an array is given as first argument).
210 */
211 protected function setMwGlobals( $pairs, $value = null ) {
212 if ( !is_array( $pairs ) ) {
213 $key = $pairs;
214 $this->mwGlobals[$key] = $GLOBALS[$key];
215 $GLOBALS[$key] = $value;
216 } else {
217 foreach ( $pairs as $key => $value ) {
218 $this->mwGlobals[$key] = $GLOBALS[$key];
219 $GLOBALS[$key] = $value;
220 }
221 }
222 }
223
224 function dbPrefix() {
225 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
226 }
227
228 function needsDB() {
229 # if the test says it uses database tables, it needs the database
230 if ( $this->tablesUsed ) {
231 return true;
232 }
233
234 # if the test says it belongs to the Database group, it needs the database
235 $rc = new ReflectionClass( $this );
236 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
237 return true;
238 }
239
240 return false;
241 }
242
243 /**
244 * Stub. If a test needs to add additional data to the database, it should
245 * implement this method and do so
246 */
247 function addDBData() {}
248
249 private function addCoreDBData() {
250 # disabled for performance
251 #$this->tablesUsed[] = 'page';
252 #$this->tablesUsed[] = 'revision';
253
254 if ( $this->db->getType() == 'oracle' ) {
255
256 # Insert 0 user to prevent FK violations
257 # Anonymous user
258 $this->db->insert( 'user', array(
259 'user_id' => 0,
260 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
261
262 # Insert 0 page to prevent FK violations
263 # Blank page
264 $this->db->insert( 'page', array(
265 'page_id' => 0,
266 'page_namespace' => 0,
267 'page_title' => ' ',
268 'page_restrictions' => NULL,
269 'page_counter' => 0,
270 'page_is_redirect' => 0,
271 'page_is_new' => 0,
272 'page_random' => 0,
273 'page_touched' => $this->db->timestamp(),
274 'page_latest' => 0,
275 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
276
277 }
278
279 User::resetIdByNameCache();
280
281 //Make sysop user
282 $user = User::newFromName( 'UTSysop' );
283
284 if ( $user->idForName() == 0 ) {
285 $user->addToDatabase();
286 $user->setPassword( 'UTSysopPassword' );
287
288 $user->addGroup( 'sysop' );
289 $user->addGroup( 'bureaucrat' );
290 $user->saveSettings();
291 }
292
293
294 //Make 1 page with 1 revision
295 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
296 if ( !$page->getId() == 0 ) {
297 $page->doEdit( 'UTContent',
298 'UTPageSummary',
299 EDIT_NEW,
300 false,
301 User::newFromName( 'UTSysop' ) );
302 }
303 }
304
305 private function initDB() {
306 global $wgDBprefix;
307 if ( $wgDBprefix === $this->dbPrefix() ) {
308 throw new MWException( 'Cannot run unit tests, the database prefix is already "unittest_"' );
309 }
310
311 $tablesCloned = $this->listTables();
312 $dbClone = new CloneDatabase( $this->db, $tablesCloned, $this->dbPrefix() );
313 $dbClone->useTemporaryTables( $this->useTemporaryTables );
314
315 if ( ( $this->db->getType() == 'oracle' || !$this->useTemporaryTables ) && $this->reuseDB ) {
316 CloneDatabase::changePrefix( $this->dbPrefix() );
317 $this->resetDB();
318 return;
319 } else {
320 $dbClone->cloneTableStructure();
321 }
322
323 if ( $this->db->getType() == 'oracle' ) {
324 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
325 }
326 }
327
328 /**
329 * Empty all tables so they can be repopulated for tests
330 */
331 private function resetDB() {
332 if( $this->db ) {
333 if ( $this->db->getType() == 'oracle' ) {
334 if ( $this->useTemporaryTables ) {
335 wfGetLB()->closeAll();
336 $this->db = wfGetDB( DB_MASTER );
337 } else {
338 foreach( $this->tablesUsed as $tbl ) {
339 if( $tbl == 'interwiki') continue;
340 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
341 }
342 }
343 } else {
344 foreach( $this->tablesUsed as $tbl ) {
345 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
346 $this->db->delete( $tbl, '*', __METHOD__ );
347 }
348 }
349 }
350 }
351
352 function __call( $func, $args ) {
353 static $compatibility = array(
354 'assertInternalType' => 'assertType',
355 'assertNotInternalType' => 'assertNotType',
356 'assertInstanceOf' => 'assertType',
357 'assertEmpty' => 'assertEmpty2',
358 );
359
360 if ( method_exists( $this->suite, $func ) ) {
361 return call_user_func_array( array( $this->suite, $func ), $args);
362 } elseif ( isset( $compatibility[$func] ) ) {
363 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
364 } else {
365 throw new MWException( "Called non-existant $func method on "
366 . get_class( $this ) );
367 }
368 }
369
370 private function assertEmpty2( $value, $msg ) {
371 return $this->assertTrue( $value == '', $msg );
372 }
373
374 static private function unprefixTable( $tableName ) {
375 global $wgDBprefix;
376 return substr( $tableName, strlen( $wgDBprefix ) );
377 }
378
379 static private function isNotUnittest( $table ) {
380 return strpos( $table, 'unittest_' ) !== 0;
381 }
382
383 protected function listTables() {
384 global $wgDBprefix;
385
386 $tables = $this->db->listTables( $wgDBprefix, __METHOD__ );
387 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
388
389 // Don't duplicate test tables from the previous fataled run
390 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
391
392 if ( $this->db->getType() == 'sqlite' ) {
393 $tables = array_flip( $tables );
394 // these are subtables of searchindex and don't need to be duped/dropped separately
395 unset( $tables['searchindex_content'] );
396 unset( $tables['searchindex_segdir'] );
397 unset( $tables['searchindex_segments'] );
398 $tables = array_flip( $tables );
399 }
400 return $tables;
401 }
402
403 protected function checkDbIsSupported() {
404 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
405 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
406 }
407 }
408
409 public function getCliArg( $offset ) {
410
411 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
412 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
413 }
414
415 }
416
417 public function setCliArg( $offset, $value ) {
418
419 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
420
421 }
422
423 /**
424 * Don't throw a warning if $function is deprecated and called later
425 *
426 * @param $function String
427 * @return null
428 */
429 function hideDeprecated( $function ) {
430 wfSuppressWarnings();
431 wfDeprecated( $function );
432 wfRestoreWarnings();
433 }
434
435 /**
436 * Asserts that the given database query yields the rows given by $expectedRows.
437 * The expected rows should be given as indexed (not associative) arrays, with
438 * the values given in the order of the columns in the $fields parameter.
439 * Note that the rows are sorted by the columns given in $fields.
440 *
441 * @since 1.20
442 *
443 * @param $table String|Array the table(s) to query
444 * @param $fields String|Array the columns to include in the result (and to sort by)
445 * @param $condition String|Array "where" condition(s)
446 * @param $expectedRows Array - an array of arrays giving the expected rows.
447 *
448 * @throws MWException if this test cases's needsDB() method doesn't return true.
449 * Test cases can use "@group Database" to enable database test support,
450 * or list the tables under testing in $this->tablesUsed, or override the
451 * needsDB() method.
452 */
453 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
454 if ( !$this->needsDB() ) {
455 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
456 ' method should return true. Use @group Database or $this->tablesUsed.');
457 }
458
459 $db = wfGetDB( DB_SLAVE );
460
461 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
462 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
463
464 $i = 0;
465
466 foreach ( $expectedRows as $expected ) {
467 $r = $res->fetchRow();
468 self::stripStringKeys( $r );
469
470 $i += 1;
471 $this->assertNotEmpty( $r, "row #$i missing" );
472
473 $this->assertEquals( $expected, $r, "row #$i mismatches" );
474 }
475
476 $r = $res->fetchRow();
477 self::stripStringKeys( $r );
478
479 $this->assertFalse( $r, "found extra row (after #$i)" );
480 }
481
482 /**
483 * Utility method taking an array of elements and wrapping
484 * each element in it's own array. Useful for data providers
485 * that only return a single argument.
486 *
487 * @since 1.20
488 *
489 * @param array $elements
490 *
491 * @return array
492 */
493 protected function arrayWrap( array $elements ) {
494 return array_map(
495 function( $element ) {
496 return array( $element );
497 },
498 $elements
499 );
500 }
501
502 /**
503 * Assert that two arrays are equal. By default this means that both arrays need to hold
504 * the same set of values. Using additional arguments, order and associated key can also
505 * be set as relevant.
506 *
507 * @since 1.20
508 *
509 * @param array $expected
510 * @param array $actual
511 * @param boolean $ordered If the order of the values should match
512 * @param boolean $named If the keys should match
513 */
514 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
515 if ( !$ordered ) {
516 $this->objectAssociativeSort( $expected );
517 $this->objectAssociativeSort( $actual );
518 }
519
520 if ( !$named ) {
521 $expected = array_values( $expected );
522 $actual = array_values( $actual );
523 }
524
525 call_user_func_array(
526 array( $this, 'assertEquals' ),
527 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
528 );
529 }
530
531 /**
532 * Put each HTML element on its own line and then equals() the results
533 *
534 * Use for nicely formatting of PHPUnit diff output when comparing very
535 * simple HTML
536 *
537 * @since 1.20
538 *
539 * @param String $expected HTML on oneline
540 * @param String $actual HTML on oneline
541 * @param String $msg Optional message
542 */
543 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
544 $expected = str_replace( '>', ">\n", $expected );
545 $actual = str_replace( '>', ">\n", $actual );
546
547 $this->assertEquals( $expected, $actual, $msg );
548 }
549
550 /**
551 * Does an associative sort that works for objects.
552 *
553 * @since 1.20
554 *
555 * @param array $array
556 */
557 protected function objectAssociativeSort( array &$array ) {
558 uasort(
559 $array,
560 function( $a, $b ) {
561 return serialize( $a ) > serialize( $b ) ? 1 : -1;
562 }
563 );
564 }
565
566 /**
567 * Utility function for eliminating all string keys from an array.
568 * Useful to turn a database result row as returned by fetchRow() into
569 * a pure indexed array.
570 *
571 * @since 1.20
572 *
573 * @param $r mixed the array to remove string keys from.
574 */
575 protected static function stripStringKeys( &$r ) {
576 if ( !is_array( $r ) ) {
577 return;
578 }
579
580 foreach ( $r as $k => $v ) {
581 if ( is_string( $k ) ) {
582 unset( $r[$k] );
583 }
584 }
585 }
586
587 /**
588 * Asserts that the provided variable is of the specified
589 * internal type or equals the $value argument. This is useful
590 * for testing return types of functions that return a certain
591 * type or *value* when not set or on error.
592 *
593 * @since 1.20
594 *
595 * @param string $type
596 * @param mixed $actual
597 * @param mixed $value
598 * @param string $message
599 */
600 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
601 if ( $actual === $value ) {
602 $this->assertTrue( true, $message );
603 }
604 else {
605 $this->assertType( $type, $actual, $message );
606 }
607 }
608
609 /**
610 * Asserts the type of the provided value. This can be either
611 * in internal type such as boolean or integer, or a class or
612 * interface the value extends or implements.
613 *
614 * @since 1.20
615 *
616 * @param string $type
617 * @param mixed $actual
618 * @param string $message
619 */
620 protected function assertType( $type, $actual, $message = '' ) {
621 if ( class_exists( $type ) || interface_exists( $type ) ) {
622 $this->assertInstanceOf( $type, $actual, $message );
623 }
624 else {
625 $this->assertInternalType( $type, $actual, $message );
626 }
627 }
628
629 }