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