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